@zuplo/runtime 6.70.27 → 6.70.29
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/esm/{chunk-H7UGARU6.js → chunk-F7DJMBWH.js} +1 -1
- package/out/esm/{chunk-H7UGARU6.js.map → chunk-F7DJMBWH.js.map} +1 -1
- package/out/esm/{chunk-P4G7GA42.js → chunk-TEXCCTJT.js} +63 -63
- package/out/esm/chunk-TEXCCTJT.js.map +1 -0
- package/out/esm/index.js +1 -1
- package/out/esm/index.js.map +1 -1
- package/out/esm/mcp-gateway/index.js +19 -21
- package/out/esm/mcp-gateway/index.js.map +1 -1
- package/out/esm/mocks/index.js +1 -1
- package/out/types/index.d.ts +36 -0
- package/out/types/mcp-gateway/index.d.ts +4 -4
- package/package.json +1 -1
- package/out/esm/chunk-P4G7GA42.js.map +0 -1
- /package/out/esm/{chunk-P4G7GA42.js.LEGAL.txt → chunk-TEXCCTJT.js.LEGAL.txt} +0 -0
|
@@ -22,22 +22,20 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{$ as rt,A as cc,B as Ct,J as Jp,K as dc,L as Iw,M as Wp,N as f,O as Yp,P as X,Q as oe,R as Qp,S as Xp,T as _e,U as C,V as I,W as Ce,X as fe,Y as lc,Z as pc,_ as de,a as Rt,aa as U,b as Zp,ba as Se,ca as em,da as mc,ea as tm,fa as rm,ga as u,ha as ae,ia as nm,j as vo,k as Kp,q as ic,s as vn,x as sc}from"../chunk-P4G7GA42.js";import{d as uc}from"../chunk-W6JQ5D4W.js";import{a as B}from"../chunk-H7UGARU6.js";import{X as Sn,Y as ue,Z as So,a as o,c as k,e as Fp}from"../chunk-JAEQKE5H.js";var oa=k(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.regexpCode=ee.getEsmExportName=ee.getProperty=ee.safeStringify=ee.stringify=ee.strConcat=ee.addCodeArg=ee.str=ee._=ee.nil=ee._Code=ee.Name=ee.IDENTIFIER=ee._CodeOrName=void 0;var ra=class{static{o(this,"_CodeOrName")}};ee._CodeOrName=ra;ee.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Jr=class extends ra{static{o(this,"Name")}constructor(t){if(super(),!ee.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};ee.Name=Jr;var lt=class extends ra{static{o(this,"_Code")}constructor(t){super(),this._items=typeof t=="string"?[t]:t}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let t=this._items[0];return t===""||t==='""'}get str(){var t;return(t=this._str)!==null&&t!==void 0?t:this._str=this._items.reduce((r,n)=>`${r}${n}`,"")}get names(){var t;return(t=this._names)!==null&&t!==void 0?t:this._names=this._items.reduce((r,n)=>(n instanceof Jr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ee._Code=lt;ee.nil=new lt("");function vg(e,...t){let r=[e[0]],n=0;for(;n<t.length;)pd(r,t[n]),r.push(e[++n]);return new lt(r)}o(vg,"_");ee._=vg;var ld=new lt("+");function _g(e,...t){let r=[na(e[0])],n=0;for(;n<t.length;)r.push(ld),pd(r,t[n]),r.push(ld,na(e[++n]));return zx(r),new lt(r)}o(_g,"str");ee.str=_g;function pd(e,t){t instanceof lt?e.push(...t._items):t instanceof Jr?e.push(t):e.push(Nx(t))}o(pd,"addCodeArg");ee.addCodeArg=pd;function zx(e){let t=1;for(;t<e.length-1;){if(e[t]===ld){let r=Mx(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}o(zx,"optimize");function Mx(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Jr||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 Jr))return`"${e}${t.slice(1)}`}o(Mx,"mergeExprItems");function qx(e,t){return t.emptyStr()?e:e.emptyStr()?t:_g`${e}${t}`}o(qx,"strConcat");ee.strConcat=qx;function Nx(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:na(Array.isArray(e)?e.join(","):e)}o(Nx,"interpolate");function Dx(e){return new lt(na(e))}o(Dx,"stringify");ee.stringify=Dx;function na(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}o(na,"safeStringify");ee.safeStringify=na;function jx(e){return typeof e=="string"&&ee.IDENTIFIER.test(e)?new lt(`.${e}`):vg`[${e}]`}o(jx,"getProperty");ee.getProperty=jx;function Hx(e){if(typeof e=="string"&&ee.IDENTIFIER.test(e))return new lt(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}o(Hx,"getEsmExportName");ee.getEsmExportName=Hx;function Lx(e){return new lt(e.toString())}o(Lx,"regexpCode");ee.regexpCode=Lx});var hd=k(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ValueScope=Xe.ValueScopeName=Xe.Scope=Xe.varKinds=Xe.UsedValueState=void 0;var Qe=oa(),md=class extends Error{static{o(this,"ValueError")}constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Hi;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Hi||(Xe.UsedValueState=Hi={}));Xe.varKinds={const:new Qe.Name("const"),let:new Qe.Name("let"),var:new Qe.Name("var")};var Li=class{static{o(this,"Scope")}constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Qe.Name?t:this.name(t)}name(t){return new Qe.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}}};Xe.Scope=Li;var Bi=class extends Qe.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,Qe._)`.${new Qe.Name(r)}[${n}]`}};Xe.ValueScopeName=Bi;var Bx=(0,Qe._)`\n`,fd=class extends Li{static{o(this,"ValueScope")}constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?Bx:Qe.nil}}get(){return this._scope}name(t){return new Bi(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,Qe._)`${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=Qe.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,Hi.Started);let l=r(p);if(l){let m=this.opts.es5?Xe.varKinds.var:Xe.varKinds.const;i=(0,Qe._)`${i}${m} ${p} = ${l};${this.opts._n}`}else if(l=a?.(p))i=(0,Qe._)`${i}${l}${this.opts._n}`;else throw new md(p);d.set(p,Hi.Completed)})}return i}};Xe.ValueScope=fd});var F=k(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.or=Z.and=Z.not=Z.CodeGen=Z.operators=Z.varKinds=Z.ValueScopeName=Z.ValueScope=Z.Scope=Z.Name=Z.regexpCode=Z.stringify=Z.getProperty=Z.nil=Z.strConcat=Z.str=Z._=void 0;var Y=oa(),St=hd(),Sr=oa();Object.defineProperty(Z,"_",{enumerable:!0,get:o(function(){return Sr._},"get")});Object.defineProperty(Z,"str",{enumerable:!0,get:o(function(){return Sr.str},"get")});Object.defineProperty(Z,"strConcat",{enumerable:!0,get:o(function(){return Sr.strConcat},"get")});Object.defineProperty(Z,"nil",{enumerable:!0,get:o(function(){return Sr.nil},"get")});Object.defineProperty(Z,"getProperty",{enumerable:!0,get:o(function(){return Sr.getProperty},"get")});Object.defineProperty(Z,"stringify",{enumerable:!0,get:o(function(){return Sr.stringify},"get")});Object.defineProperty(Z,"regexpCode",{enumerable:!0,get:o(function(){return Sr.regexpCode},"get")});Object.defineProperty(Z,"Name",{enumerable:!0,get:o(function(){return Sr.Name},"get")});var Zi=hd();Object.defineProperty(Z,"Scope",{enumerable:!0,get:o(function(){return Zi.Scope},"get")});Object.defineProperty(Z,"ValueScope",{enumerable:!0,get:o(function(){return Zi.ValueScope},"get")});Object.defineProperty(Z,"ValueScopeName",{enumerable:!0,get:o(function(){return Zi.ValueScopeName},"get")});Object.defineProperty(Z,"varKinds",{enumerable:!0,get:o(function(){return Zi.varKinds},"get")});Z.operators={GT:new Y._Code(">"),GTE:new Y._Code(">="),LT:new Y._Code("<"),LTE:new Y._Code("<="),EQ:new Y._Code("==="),NEQ:new Y._Code("!=="),NOT:new Y._Code("!"),OR:new Y._Code("||"),AND:new Y._Code("&&"),ADD:new Y._Code("+")};var Kt=class{static{o(this,"Node")}optimizeNodes(){return this}optimizeNames(t,r){return this}},gd=class extends Kt{static{o(this,"Def")}constructor(t,r,n){super(),this.varKind=t,this.name=r,this.rhs=n}render({es5:t,_n:r}){let n=t?St.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=Bn(this.rhs,t,r)),this}get names(){return this.rhs instanceof Y._CodeOrName?this.rhs.names:{}}},Gi=class extends Kt{static{o(this,"Assign")}constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof Y.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Bn(this.rhs,t,r),this}get names(){let t=this.lhs instanceof Y.Name?{}:{...this.lhs.names};return Fi(t,this.rhs)}},yd=class extends Gi{static{o(this,"AssignOp")}constructor(t,r,n,a){super(t,n,a),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Sd=class extends Kt{static{o(this,"Label")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},vd=class extends Kt{static{o(this,"Break")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},_d=class extends Kt{static{o(this,"Throw")}constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},wd=class extends Kt{static{o(this,"AnyCode")}constructor(t){super(),this.code=t}render({_n:t}){return`${this.code};`+t}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(t,r){return this.code=Bn(this.code,t,r),this}get names(){return this.code instanceof Y._CodeOrName?this.code.names:{}}},aa=class extends Kt{static{o(this,"ParentNode")}constructor(t=[]){super(),this.nodes=t}render(t){return this.nodes.reduce((r,n)=>r+n.render(t),"")}optimizeNodes(){let{nodes:t}=this,r=t.length;for(;r--;){let n=t[r].optimizeNodes();Array.isArray(n)?t.splice(r,1,...n):n?t[r]=n:t.splice(r,1)}return t.length>0?this:void 0}optimizeNames(t,r){let{nodes:n}=this,a=n.length;for(;a--;){let i=n[a];i.optimizeNames(t,r)||(Gx(t,i.names),n.splice(a,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>Qr(t,r.names),{})}},Jt=class extends aa{static{o(this,"BlockNode")}render(t){return"{"+t._n+super.render(t)+"}"+t._n}},bd=class extends aa{static{o(this,"Root")}},Ln=class extends Jt{static{o(this,"Else")}};Ln.kind="else";var Wr=class e extends Jt{static{o(this,"If")}constructor(t,r){super(r),this.condition=t}render(t){let r=`if(${this.condition})`+super.render(t);return this.else&&(r+="else "+this.else.render(t)),r}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let r=this.else;if(r){let n=r.optimizeNodes();r=this.else=Array.isArray(n)?new Ln(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(wg(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=Bn(this.condition,t,r),this}get names(){let t=super.names;return Fi(t,this.condition),this.else&&Qr(t,this.else.names),t}};Wr.kind="if";var Yr=class extends Jt{static{o(this,"For")}};Yr.kind="for";var Rd=class extends Yr{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=Bn(this.iteration,t,r),this}get names(){return Qr(super.names,this.iteration.names)}},Cd=class extends Yr{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?St.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=Fi(super.names,this.from);return Fi(t,this.to)}},Vi=class extends Yr{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=Bn(this.iterable,t,r),this}get names(){return Qr(super.names,this.iterable.names)}},ia=class extends Jt{static{o(this,"Func")}constructor(t,r,n){super(),this.name=t,this.args=r,this.async=n}render(t){return`${this.async?"async ":""}function ${this.name}(${this.args})`+super.render(t)}};ia.kind="func";var sa=class extends aa{static{o(this,"Return")}render(t){return"return "+super.render(t)}};sa.kind="return";var Id=class extends Jt{static{o(this,"Try")}render(t){let r="try"+super.render(t);return this.catch&&(r+=this.catch.render(t)),this.finally&&(r+=this.finally.render(t)),r}optimizeNodes(){var t,r;return super.optimizeNodes(),(t=this.catch)===null||t===void 0||t.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(t,r){var n,a;return super.optimizeNames(t,r),(n=this.catch)===null||n===void 0||n.optimizeNames(t,r),(a=this.finally)===null||a===void 0||a.optimizeNames(t,r),this}get names(){let t=super.names;return this.catch&&Qr(t,this.catch.names),this.finally&&Qr(t,this.finally.names),t}},ca=class extends Jt{static{o(this,"Catch")}constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};ca.kind="catch";var ua=class extends Jt{static{o(this,"Finally")}render(t){return"finally"+super.render(t)}};ua.kind="finally";var Pd=class{static{o(this,"CodeGen")}constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
26
|
-
`:""},this._extScope=t,this._scope=new St.Scope({parent:t}),this._nodes=[new bd]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,a){let i=this._scope.toName(r);return n!==void 0&&a&&(this._constants[i.str]=n),this._leafNode(new gd(t,i,n)),i}const(t,r,n){return this._def(St.varKinds.const,t,r,n)}let(t,r,n){return this._def(St.varKinds.let,t,r,n)}var(t,r,n){return this._def(St.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Gi(t,r,n))}add(t,r){return this._leafNode(new yd(t,Z.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==Y.nil&&this._leafNode(new wd(t)),this}object(...t){let r=["{"];for(let[n,a]of t)r.length>1&&r.push(","),r.push(n),(n!==a||this.opts.es5)&&(r.push(":"),(0,Y.addCodeArg)(r,a));return r.push("}"),new Y._Code(r)}if(t,r,n){if(this._blockNode(new Wr(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 Wr(t))}else(){return this._elseNode(new Ln)}endIf(){return this._endBlockNode(Wr,Ln)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Rd(t),r)}forRange(t,r,n,a,i=this.opts.es5?St.varKinds.var:St.varKinds.let){let s=this._scope.toName(t);return this._for(new Cd(i,s,r,n),()=>a(s))}forOf(t,r,n,a=St.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof Y.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Y._)`${s}.length`,c=>{this.var(i,(0,Y._)`${s}[${c}]`),n(i)})}return this._for(new Vi("of",a,i,r),()=>n(i))}forIn(t,r,n,a=this.opts.es5?St.varKinds.var:St.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,Y._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new Vi("in",a,i,r),()=>n(i))}endFor(){return this._endBlockNode(Yr)}label(t){return this._leafNode(new Sd(t))}break(t){return this._leafNode(new vd(t))}return(t){let r=new sa;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(sa)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let a=new Id;if(this._blockNode(a),this.code(t),r){let i=this.name("e");this._currNode=a.catch=new ca(i),r(i)}return n&&(this._currNode=a.finally=new ua,this.code(n)),this._endBlockNode(ca,ua)}throw(t){return this._leafNode(new _d(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=Y.nil,n,a){return this._blockNode(new ia(t,r,n)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(ia)}optimize(t=1){for(;t-- >0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(t){return this._currNode.nodes.push(t),this}_blockNode(t){this._currNode.nodes.push(t),this._nodes.push(t)}_endBlockNode(t,r){let n=this._currNode;if(n instanceof t||r&&n instanceof r)return this._nodes.pop(),this;throw new Error(`CodeGen: not in block "${r?`${t.kind}/${r.kind}`:t.kind}"`)}_elseNode(t){let r=this._currNode;if(!(r instanceof Wr))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};Z.CodeGen=Pd;function Qr(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}o(Qr,"addNames");function Fi(e,t){return t instanceof Y._CodeOrName?Qr(e,t.names):e}o(Fi,"addExprNames");function Bn(e,t,r){if(e instanceof Y.Name)return n(e);if(!a(e))return e;return new Y._Code(e._items.reduce((i,s)=>(s instanceof Y.Name&&(s=n(s)),s instanceof Y._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function a(i){return i instanceof Y._Code&&i._items.some(s=>s instanceof Y.Name&&t[s.str]===1&&r[s.str]!==void 0)}}o(Bn,"optimizeExpr");function Gx(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}o(Gx,"subtractNames");function wg(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,Y._)`!${xd(e)}`}o(wg,"not");Z.not=wg;var Vx=bg(Z.operators.AND);function Fx(...e){return e.reduce(Vx)}o(Fx,"and");Z.and=Fx;var Zx=bg(Z.operators.OR);function Kx(...e){return e.reduce(Zx)}o(Kx,"or");Z.or=Kx;function bg(e){return(t,r)=>t===Y.nil?r:r===Y.nil?t:(0,Y._)`${xd(t)} ${e} ${xd(r)}`}o(bg,"mappend");function xd(e){return e instanceof Y.Name?e:(0,Y._)`(${e})`}o(xd,"par")});var te=k(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.checkStrictMode=J.getErrorPath=J.Type=J.useFunc=J.setEvaluated=J.evaluatedPropsToName=J.mergeEvaluated=J.eachItem=J.unescapeJsonPointer=J.escapeJsonPointer=J.escapeFragment=J.unescapeFragment=J.schemaRefOrVal=J.schemaHasRulesButRef=J.schemaHasRules=J.checkUnknownRules=J.alwaysValidSchema=J.toHash=void 0;var se=F(),Jx=oa();function Wx(e){let t={};for(let r of e)t[r]=!0;return t}o(Wx,"toHash");J.toHash=Wx;function Yx(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Ig(e,t),!Pg(t,e.self.RULES.all))}o(Yx,"alwaysValidSchema");J.alwaysValidSchema=Yx;function Ig(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]||Tg(e,`unknown keyword: "${i}"`)}o(Ig,"checkUnknownRules");J.checkUnknownRules=Ig;function Pg(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}o(Pg,"schemaHasRules");J.schemaHasRules=Pg;function Qx(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}o(Qx,"schemaHasRulesButRef");J.schemaHasRulesButRef=Qx;function Xx({topSchemaRef:e,schemaPath:t},r,n,a){if(!a){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,se._)`${r}`}return(0,se._)`${e}${t}${(0,se.getProperty)(n)}`}o(Xx,"schemaRefOrVal");J.schemaRefOrVal=Xx;function ek(e){return xg(decodeURIComponent(e))}o(ek,"unescapeFragment");J.unescapeFragment=ek;function tk(e){return encodeURIComponent(Td(e))}o(tk,"escapeFragment");J.escapeFragment=tk;function Td(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}o(Td,"escapeJsonPointer");J.escapeJsonPointer=Td;function xg(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}o(xg,"unescapeJsonPointer");J.unescapeJsonPointer=xg;function rk(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}o(rk,"eachItem");J.eachItem=rk;function Rg({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(a,i,s,c)=>{let d=s===void 0?i:s instanceof se.Name?(i instanceof se.Name?e(a,i,s):t(a,i,s),s):i instanceof se.Name?(t(a,s,i),i):r(i,s);return c===se.Name&&!(d instanceof se.Name)?n(a,d):d}}o(Rg,"makeMergeEvaluated");J.mergeEvaluated={props:Rg({mergeNames:o((e,t,r)=>e.if((0,se._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,se._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,se._)`${r} || {}`).code((0,se._)`Object.assign(${r}, ${t})`))}),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,se._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,se._)`${r} || {}`),Ad(e,r,t))}),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:{...e,...t},"mergeValues"),resultToName:kg}),items:Rg({mergeNames:o((e,t,r)=>e.if((0,se._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,se._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,se._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,se._)`${r} > ${t} ? ${r} : ${t}`)),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:Math.max(e,t),"mergeValues"),resultToName:o((e,t)=>e.var("items",t),"resultToName")})};function kg(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,se._)`{}`);return t!==void 0&&Ad(e,r,t),r}o(kg,"evaluatedPropsToName");J.evaluatedPropsToName=kg;function Ad(e,t,r){Object.keys(r).forEach(n=>e.assign((0,se._)`${t}${(0,se.getProperty)(n)}`,!0))}o(Ad,"setEvaluated");J.setEvaluated=Ad;var Cg={};function nk(e,t){return e.scopeValue("func",{ref:t,code:Cg[t.code]||(Cg[t.code]=new Jx._Code(t.code))})}o(nk,"useFunc");J.useFunc=nk;var kd;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(kd||(J.Type=kd={}));function ok(e,t,r){if(e instanceof se.Name){let n=t===kd.Num;return r?n?(0,se._)`"[" + ${e} + "]"`:(0,se._)`"['" + ${e} + "']"`:n?(0,se._)`"/" + ${e}`:(0,se._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,se.getProperty)(e).toString():"/"+Td(e)}o(ok,"getErrorPath");J.getErrorPath=ok;function Tg(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(Tg,"checkStrictMode");J.checkStrictMode=Tg});var Wt=k(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var je=F(),ak={data:new je.Name("data"),valCxt:new je.Name("valCxt"),instancePath:new je.Name("instancePath"),parentData:new je.Name("parentData"),parentDataProperty:new je.Name("parentDataProperty"),rootData:new je.Name("rootData"),dynamicAnchors:new je.Name("dynamicAnchors"),vErrors:new je.Name("vErrors"),errors:new je.Name("errors"),this:new je.Name("this"),self:new je.Name("self"),scope:new je.Name("scope"),json:new je.Name("json"),jsonPos:new je.Name("jsonPos"),jsonLen:new je.Name("jsonLen"),jsonPart:new je.Name("jsonPart")};Ed.default=ak});var da=k(He=>{"use strict";Object.defineProperty(He,"__esModule",{value:!0});He.extendErrors=He.resetErrorsCount=He.reportExtraError=He.reportError=He.keyword$DataError=He.keywordError=void 0;var Q=F(),Ki=te(),Ve=Wt();He.keywordError={message:o(({keyword:e})=>(0,Q.str)`must pass "${e}" keyword validation`,"message")};He.keyword$DataError={message:o(({keyword:e,schemaType:t})=>t?(0,Q.str)`"${e}" keyword must be ${t} ($data)`:(0,Q.str)`"${e}" keyword is invalid ($data)`,"message")};function ik(e,t=He.keywordError,r,n){let{it:a}=e,{gen:i,compositeRule:s,allErrors:c}=a,d=Ug(e,t,r);n??(s||c)?Ag(i,d):Eg(a,(0,Q._)`[${d}]`)}o(ik,"reportError");He.reportError=ik;function sk(e,t=He.keywordError,r){let{it:n}=e,{gen:a,compositeRule:i,allErrors:s}=n,c=Ug(e,t,r);Ag(a,c),i||s||Eg(n,Ve.default.vErrors)}o(sk,"reportExtraError");He.reportExtraError=sk;function ck(e,t){e.assign(Ve.default.errors,t),e.if((0,Q._)`${Ve.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Q._)`${Ve.default.vErrors}.length`,t),()=>e.assign(Ve.default.vErrors,null)))}o(ck,"resetErrorsCount");He.resetErrorsCount=ck;function uk({gen:e,keyword:t,schemaValue:r,data:n,errsCount:a,it:i}){if(a===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",a,Ve.default.errors,c=>{e.const(s,(0,Q._)`${Ve.default.vErrors}[${c}]`),e.if((0,Q._)`${s}.instancePath === undefined`,()=>e.assign((0,Q._)`${s}.instancePath`,(0,Q.strConcat)(Ve.default.instancePath,i.errorPath))),e.assign((0,Q._)`${s}.schemaPath`,(0,Q.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,Q._)`${s}.schema`,r),e.assign((0,Q._)`${s}.data`,n))})}o(uk,"extendErrors");He.extendErrors=uk;function Ag(e,t){let r=e.const("err",t);e.if((0,Q._)`${Ve.default.vErrors} === null`,()=>e.assign(Ve.default.vErrors,(0,Q._)`[${r}]`),(0,Q._)`${Ve.default.vErrors}.push(${r})`),e.code((0,Q._)`${Ve.default.errors}++`)}o(Ag,"addError");function Eg(e,t){let{gen:r,validateName:n,schemaEnv:a}=e;a.$async?r.throw((0,Q._)`new ${e.ValidationError}(${t})`):(r.assign((0,Q._)`${n}.errors`,t),r.return(!1))}o(Eg,"returnErrors");var Xr={keyword:new Q.Name("keyword"),schemaPath:new Q.Name("schemaPath"),params:new Q.Name("params"),propertyName:new Q.Name("propertyName"),message:new Q.Name("message"),schema:new Q.Name("schema"),parentSchema:new Q.Name("parentSchema")};function Ug(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Q._)`{}`:dk(e,t,r)}o(Ug,"errorObjectCode");function dk(e,t,r={}){let{gen:n,it:a}=e,i=[lk(a,r),pk(e,r)];return mk(e,t,i),n.object(...i)}o(dk,"errorObject");function lk({errorPath:e},{instancePath:t}){let r=t?(0,Q.str)`${e}${(0,Ki.getErrorPath)(t,Ki.Type.Str)}`:e;return[Ve.default.instancePath,(0,Q.strConcat)(Ve.default.instancePath,r)]}o(lk,"errorInstancePath");function pk({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let a=n?t:(0,Q.str)`${t}/${e}`;return r&&(a=(0,Q.str)`${a}${(0,Ki.getErrorPath)(r,Ki.Type.Str)}`),[Xr.schemaPath,a]}o(pk,"errorSchemaPath");function mk(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([Xr.keyword,a],[Xr.params,typeof t=="function"?t(e):t||(0,Q._)`{}`]),d.messages&&n.push([Xr.message,typeof r=="function"?r(e):r]),d.verbose&&n.push([Xr.schema,s],[Xr.parentSchema,(0,Q._)`${l}${m}`],[Ve.default.data,i]),p&&n.push([Xr.propertyName,p])}o(mk,"extraErrorProps")});var $g=k(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.boolOrEmptySchema=Gn.topBoolOrEmptySchema=void 0;var fk=da(),hk=F(),gk=Wt(),yk={message:"boolean schema is false"};function Sk(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Og(e,!1):typeof r=="object"&&r.$async===!0?t.return(gk.default.data):(t.assign((0,hk._)`${n}.errors`,null),t.return(!0))}o(Sk,"topBoolOrEmptySchema");Gn.topBoolOrEmptySchema=Sk;function vk(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Og(e)):r.var(t,!0)}o(vk,"boolOrEmptySchema");Gn.boolOrEmptySchema=vk;function Og(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,fk.reportError)(a,yk,void 0,t)}o(Og,"falseSchemaError")});var Ud=k(Vn=>{"use strict";Object.defineProperty(Vn,"__esModule",{value:!0});Vn.getRules=Vn.isJSONType=void 0;var _k=["string","number","integer","boolean","null","object","array"],wk=new Set(_k);function bk(e){return typeof e=="string"&&wk.has(e)}o(bk,"isJSONType");Vn.isJSONType=bk;function Rk(){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(Rk,"getRules");Vn.getRules=Rk});var Od=k(vr=>{"use strict";Object.defineProperty(vr,"__esModule",{value:!0});vr.shouldUseRule=vr.shouldUseGroup=vr.schemaHasRulesForType=void 0;function Ck({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&zg(e,n)}o(Ck,"schemaHasRulesForType");vr.schemaHasRulesForType=Ck;function zg(e,t){return t.rules.some(r=>Mg(e,r))}o(zg,"shouldUseGroup");vr.shouldUseGroup=zg;function Mg(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(Mg,"shouldUseRule");vr.shouldUseRule=Mg});var la=k(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.reportTypeError=Le.checkDataTypes=Le.checkDataType=Le.coerceAndCheckDataType=Le.getJSONTypes=Le.getSchemaTypes=Le.DataType=void 0;var Ik=Ud(),Pk=Od(),xk=da(),G=F(),qg=te(),Fn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Fn||(Le.DataType=Fn={}));function kk(e){let t=Ng(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(kk,"getSchemaTypes");Le.getSchemaTypes=kk;function Ng(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Ik.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}o(Ng,"getJSONTypes");Le.getJSONTypes=Ng;function Tk(e,t){let{gen:r,data:n,opts:a}=e,i=Ak(t,a.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,Pk.schemaHasRulesForType)(e,t[0]));if(s){let c=zd(t,n,a.strictNumbers,Fn.Wrong);r.if(c,()=>{i.length?Ek(e,t,i):Md(e)})}return s}o(Tk,"coerceAndCheckDataType");Le.coerceAndCheckDataType=Tk;var Dg=new Set(["string","number","integer","boolean","null"]);function Ak(e,t){return t?e.filter(r=>Dg.has(r)||t==="array"&&r==="array"):[]}o(Ak,"coerceToTypes");function Ek(e,t,r){let{gen:n,data:a,opts:i}=e,s=n.let("dataType",(0,G._)`typeof ${a}`),c=n.let("coerced",(0,G._)`undefined`);i.coerceTypes==="array"&&n.if((0,G._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>n.assign(a,(0,G._)`${a}[0]`).assign(s,(0,G._)`typeof ${a}`).if(zd(t,a,i.strictNumbers),()=>n.assign(c,a))),n.if((0,G._)`${c} !== undefined`);for(let p of r)(Dg.has(p)||p==="array"&&i.coerceTypes==="array")&&d(p);n.else(),Md(e),n.endIf(),n.if((0,G._)`${c} !== undefined`,()=>{n.assign(a,c),Uk(e,c)});function d(p){switch(p){case"string":n.elseIf((0,G._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,G._)`"" + ${a}`).elseIf((0,G._)`${a} === null`).assign(c,(0,G._)`""`);return;case"number":n.elseIf((0,G._)`${s} == "boolean" || ${a} === null
|
|
25
|
+
import{$ as nt,A as uc,B as kt,J as Wp,K as dc,L as Uw,M as Yp,N as f,O as Qp,P as X,Q as oe,R as Xp,S as em,T as _e,U as C,V as I,W as Ce,X as fe,Y as lc,Z as pc,_ as ce,a as xt,aa as U,b as Kp,ba as Se,ca as tm,da as mc,ea as rm,fa as nm,ga as u,ha as ue,ia as om,j as bo,k as Jp,q as sc,s as Rn,x as cc}from"../chunk-TEXCCTJT.js";import{d as Ja}from"../chunk-W6JQ5D4W.js";import{a as B}from"../chunk-F7DJMBWH.js";import{X as bn,Y as de,Z as wo,a as o,c as k,e as Zp}from"../chunk-JAEQKE5H.js";var ia=k(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.regexpCode=ee.getEsmExportName=ee.getProperty=ee.safeStringify=ee.stringify=ee.strConcat=ee.addCodeArg=ee.str=ee._=ee.nil=ee._Code=ee.Name=ee.IDENTIFIER=ee._CodeOrName=void 0;var oa=class{static{o(this,"_CodeOrName")}};ee._CodeOrName=oa;ee.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Xr=class extends oa{static{o(this,"Name")}constructor(t){if(super(),!ee.IDENTIFIER.test(t))throw new Error("CodeGen: name must be a valid identifier");this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};ee.Name=Xr;var ht=class extends oa{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 Xr&&(r[n.str]=(r[n.str]||0)+1),r),{})}};ee._Code=ht;ee.nil=new ht("");function Tg(e,...t){let r=[e[0]],n=0;for(;n<t.length;)pd(r,t[n]),r.push(e[++n]);return new ht(r)}o(Tg,"_");ee._=Tg;var ld=new ht("+");function Ag(e,...t){let r=[aa(e[0])],n=0;for(;n<t.length;)r.push(ld),pd(r,t[n]),r.push(ld,aa(e[++n]));return Lx(r),new ht(r)}o(Ag,"str");ee.str=Ag;function pd(e,t){t instanceof ht?e.push(...t._items):t instanceof Xr?e.push(t):e.push(Vx(t))}o(pd,"addCodeArg");ee.addCodeArg=pd;function Lx(e){let t=1;for(;t<e.length-1;){if(e[t]===ld){let r=Bx(e[t-1],e[t+1]);if(r!==void 0){e.splice(t-1,3,r);continue}e[t++]="+"}t++}}o(Lx,"optimize");function Bx(e,t){if(t==='""')return e;if(e==='""')return t;if(typeof e=="string")return t instanceof Xr||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 Xr))return`"${e}${t.slice(1)}`}o(Bx,"mergeExprItems");function Gx(e,t){return t.emptyStr()?e:e.emptyStr()?t:Ag`${e}${t}`}o(Gx,"strConcat");ee.strConcat=Gx;function Vx(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:aa(Array.isArray(e)?e.join(","):e)}o(Vx,"interpolate");function Fx(e){return new ht(aa(e))}o(Fx,"stringify");ee.stringify=Fx;function aa(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}o(aa,"safeStringify");ee.safeStringify=aa;function Zx(e){return typeof e=="string"&&ee.IDENTIFIER.test(e)?new ht(`.${e}`):Tg`[${e}]`}o(Zx,"getProperty");ee.getProperty=Zx;function Kx(e){if(typeof e=="string"&&ee.IDENTIFIER.test(e))return new ht(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}o(Kx,"getEsmExportName");ee.getEsmExportName=Kx;function Jx(e){return new ht(e.toString())}o(Jx,"regexpCode");ee.regexpCode=Jx});var hd=k(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.ValueScope=et.ValueScopeName=et.Scope=et.varKinds=et.UsedValueState=void 0;var Xe=ia(),md=class extends Error{static{o(this,"ValueError")}constructor(t){super(`CodeGen: "code" for ${t} not defined`),this.value=t.value}},Gi;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(Gi||(et.UsedValueState=Gi={}));et.varKinds={const:new Xe.Name("const"),let:new Xe.Name("let"),var:new Xe.Name("var")};var Vi=class{static{o(this,"Scope")}constructor({prefixes:t,parent:r}={}){this._names={},this._prefixes=t,this._parent=r}toName(t){return t instanceof Xe.Name?t:this.name(t)}name(t){return new Xe.Name(this._newName(t))}_newName(t){let r=this._names[t]||this._nameGroup(t);return`${t}${r.index++}`}_nameGroup(t){var r,n;if(!((n=(r=this._parent)===null||r===void 0?void 0:r._prefixes)===null||n===void 0)&&n.has(t)||this._prefixes&&!this._prefixes.has(t))throw new Error(`CodeGen: prefix "${t}" is not allowed in this scope`);return this._names[t]={prefix:t,index:0}}};et.Scope=Vi;var Fi=class extends Xe.Name{static{o(this,"ValueScopeName")}constructor(t,r){super(r),this.prefix=t}setValue(t,{property:r,itemIndex:n}){this.value=t,this.scopePath=(0,Xe._)`.${new Xe.Name(r)}[${n}]`}};et.ValueScopeName=Fi;var Wx=(0,Xe._)`\n`,fd=class extends Vi{static{o(this,"ValueScope")}constructor(t){super(t),this._values={},this._scope=t.scope,this.opts={...t,_n:t.lines?Wx:Xe.nil}}get(){return this._scope}name(t){return new Fi(t,this._newName(t))}value(t,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let a=this.toName(t),{prefix:i}=a,s=(n=r.key)!==null&&n!==void 0?n:r.ref,c=this._values[i];if(c){let l=c.get(s);if(l)return l}else c=this._values[i]=new Map;c.set(s,a);let d=this._scope[i]||(this._scope[i]=[]),p=d.length;return d[p]=r.ref,a.setValue(r,{property:i,itemIndex:p}),a}getValue(t,r){let n=this._values[t];if(n)return n.get(r)}scopeRefs(t,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,Xe._)`${t}${n.scopePath}`})}scopeCode(t=this._values,r,n){return this._reduceValues(t,a=>{if(a.value===void 0)throw new Error(`CodeGen: name "${a}" has no value`);return a.value.code},r,n)}_reduceValues(t,r,n={},a){let i=Xe.nil;for(let s in t){let c=t[s];if(!c)continue;let d=n[s]=n[s]||new Map;c.forEach(p=>{if(d.has(p))return;d.set(p,Gi.Started);let l=r(p);if(l){let m=this.opts.es5?et.varKinds.var:et.varKinds.const;i=(0,Xe._)`${i}${m} ${p} = ${l};${this.opts._n}`}else if(l=a?.(p))i=(0,Xe._)`${i}${l}${this.opts._n}`;else throw new md(p);d.set(p,Gi.Completed)})}return i}};et.ValueScope=fd});var F=k(Z=>{"use strict";Object.defineProperty(Z,"__esModule",{value:!0});Z.or=Z.and=Z.not=Z.CodeGen=Z.operators=Z.varKinds=Z.ValueScopeName=Z.ValueScope=Z.Scope=Z.Name=Z.regexpCode=Z.stringify=Z.getProperty=Z.nil=Z.strConcat=Z.str=Z._=void 0;var Y=ia(),bt=hd(),Cr=ia();Object.defineProperty(Z,"_",{enumerable:!0,get:o(function(){return Cr._},"get")});Object.defineProperty(Z,"str",{enumerable:!0,get:o(function(){return Cr.str},"get")});Object.defineProperty(Z,"strConcat",{enumerable:!0,get:o(function(){return Cr.strConcat},"get")});Object.defineProperty(Z,"nil",{enumerable:!0,get:o(function(){return Cr.nil},"get")});Object.defineProperty(Z,"getProperty",{enumerable:!0,get:o(function(){return Cr.getProperty},"get")});Object.defineProperty(Z,"stringify",{enumerable:!0,get:o(function(){return Cr.stringify},"get")});Object.defineProperty(Z,"regexpCode",{enumerable:!0,get:o(function(){return Cr.regexpCode},"get")});Object.defineProperty(Z,"Name",{enumerable:!0,get:o(function(){return Cr.Name},"get")});var Wi=hd();Object.defineProperty(Z,"Scope",{enumerable:!0,get:o(function(){return Wi.Scope},"get")});Object.defineProperty(Z,"ValueScope",{enumerable:!0,get:o(function(){return Wi.ValueScope},"get")});Object.defineProperty(Z,"ValueScopeName",{enumerable:!0,get:o(function(){return Wi.ValueScopeName},"get")});Object.defineProperty(Z,"varKinds",{enumerable:!0,get:o(function(){return Wi.varKinds},"get")});Z.operators={GT:new Y._Code(">"),GTE:new Y._Code(">="),LT:new Y._Code("<"),LTE:new Y._Code("<="),EQ:new Y._Code("==="),NEQ:new Y._Code("!=="),NOT:new Y._Code("!"),OR:new Y._Code("||"),AND:new Y._Code("&&"),ADD:new Y._Code("+")};var Yt=class{static{o(this,"Node")}optimizeNodes(){return this}optimizeNames(t,r){return this}},gd=class extends Yt{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?bt.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=Fn(this.rhs,t,r)),this}get names(){return this.rhs instanceof Y._CodeOrName?this.rhs.names:{}}},Zi=class extends Yt{static{o(this,"Assign")}constructor(t,r,n){super(),this.lhs=t,this.rhs=r,this.sideEffects=n}render({_n:t}){return`${this.lhs} = ${this.rhs};`+t}optimizeNames(t,r){if(!(this.lhs instanceof Y.Name&&!t[this.lhs.str]&&!this.sideEffects))return this.rhs=Fn(this.rhs,t,r),this}get names(){let t=this.lhs instanceof Y.Name?{}:{...this.lhs.names};return Ji(t,this.rhs)}},yd=class extends Zi{static{o(this,"AssignOp")}constructor(t,r,n,a){super(t,n,a),this.op=r}render({_n:t}){return`${this.lhs} ${this.op}= ${this.rhs};`+t}},Sd=class extends Yt{static{o(this,"Label")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`${this.label}:`+t}},vd=class extends Yt{static{o(this,"Break")}constructor(t){super(),this.label=t,this.names={}}render({_n:t}){return`break${this.label?` ${this.label}`:""};`+t}},_d=class extends Yt{static{o(this,"Throw")}constructor(t){super(),this.error=t}render({_n:t}){return`throw ${this.error};`+t}get names(){return this.error.names}},wd=class extends Yt{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=Fn(this.code,t,r),this}get names(){return this.code instanceof Y._CodeOrName?this.code.names:{}}},sa=class extends Yt{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)||(Yx(t,i.names),n.splice(a,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((t,r)=>rn(t,r.names),{})}},Qt=class extends sa{static{o(this,"BlockNode")}render(t){return"{"+t._n+super.render(t)+"}"+t._n}},bd=class extends sa{static{o(this,"Root")}},Vn=class extends Qt{static{o(this,"Else")}};Vn.kind="else";var en=class e extends Qt{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 Vn(n):n}if(r)return t===!1?r instanceof e?r:r.nodes:this.nodes.length?this:new e(Eg(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=Fn(this.condition,t,r),this}get names(){let t=super.names;return Ji(t,this.condition),this.else&&rn(t,this.else.names),t}};en.kind="if";var tn=class extends Qt{static{o(this,"For")}};tn.kind="for";var Rd=class extends tn{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=Fn(this.iteration,t,r),this}get names(){return rn(super.names,this.iteration.names)}},Cd=class extends tn{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?bt.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=Ji(super.names,this.from);return Ji(t,this.to)}},Ki=class extends tn{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=Fn(this.iterable,t,r),this}get names(){return rn(super.names,this.iterable.names)}},ca=class extends Qt{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)}};ca.kind="func";var ua=class extends sa{static{o(this,"Return")}render(t){return"return "+super.render(t)}};ua.kind="return";var Id=class extends Qt{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&&rn(t,this.catch.names),this.finally&&rn(t,this.finally.names),t}},da=class extends Qt{static{o(this,"Catch")}constructor(t){super(),this.error=t}render(t){return`catch(${this.error})`+super.render(t)}};da.kind="catch";var la=class extends Qt{static{o(this,"Finally")}render(t){return"finally"+super.render(t)}};la.kind="finally";var Pd=class{static{o(this,"CodeGen")}constructor(t,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
|
|
26
|
+
`:""},this._extScope=t,this._scope=new bt.Scope({parent:t}),this._nodes=[new bd]}toString(){return this._root.render(this.opts)}name(t){return this._scope.name(t)}scopeName(t){return this._extScope.name(t)}scopeValue(t,r){let n=this._extScope.value(t,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(t,r){return this._extScope.getValue(t,r)}scopeRefs(t){return this._extScope.scopeRefs(t,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(t,r,n,a){let i=this._scope.toName(r);return n!==void 0&&a&&(this._constants[i.str]=n),this._leafNode(new gd(t,i,n)),i}const(t,r,n){return this._def(bt.varKinds.const,t,r,n)}let(t,r,n){return this._def(bt.varKinds.let,t,r,n)}var(t,r,n){return this._def(bt.varKinds.var,t,r,n)}assign(t,r,n){return this._leafNode(new Zi(t,r,n))}add(t,r){return this._leafNode(new yd(t,Z.operators.ADD,r))}code(t){return typeof t=="function"?t():t!==Y.nil&&this._leafNode(new wd(t)),this}object(...t){let r=["{"];for(let[n,a]of t)r.length>1&&r.push(","),r.push(n),(n!==a||this.opts.es5)&&(r.push(":"),(0,Y.addCodeArg)(r,a));return r.push("}"),new Y._Code(r)}if(t,r,n){if(this._blockNode(new en(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 en(t))}else(){return this._elseNode(new Vn)}endIf(){return this._endBlockNode(en,Vn)}_for(t,r){return this._blockNode(t),r&&this.code(r).endFor(),this}for(t,r){return this._for(new Rd(t),r)}forRange(t,r,n,a,i=this.opts.es5?bt.varKinds.var:bt.varKinds.let){let s=this._scope.toName(t);return this._for(new Cd(i,s,r,n),()=>a(s))}forOf(t,r,n,a=bt.varKinds.const){let i=this._scope.toName(t);if(this.opts.es5){let s=r instanceof Y.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,Y._)`${s}.length`,c=>{this.var(i,(0,Y._)`${s}[${c}]`),n(i)})}return this._for(new Ki("of",a,i,r),()=>n(i))}forIn(t,r,n,a=this.opts.es5?bt.varKinds.var:bt.varKinds.const){if(this.opts.ownProperties)return this.forOf(t,(0,Y._)`Object.keys(${r})`,n);let i=this._scope.toName(t);return this._for(new Ki("in",a,i,r),()=>n(i))}endFor(){return this._endBlockNode(tn)}label(t){return this._leafNode(new Sd(t))}break(t){return this._leafNode(new vd(t))}return(t){let r=new ua;if(this._blockNode(r),this.code(t),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(ua)}try(t,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let a=new Id;if(this._blockNode(a),this.code(t),r){let i=this.name("e");this._currNode=a.catch=new da(i),r(i)}return n&&(this._currNode=a.finally=new la,this.code(n)),this._endBlockNode(da,la)}throw(t){return this._leafNode(new _d(t))}block(t,r){return this._blockStarts.push(this._nodes.length),t&&this.code(t).endBlock(r),this}endBlock(t){let r=this._blockStarts.pop();if(r===void 0)throw new Error("CodeGen: not in self-balancing block");let n=this._nodes.length-r;if(n<0||t!==void 0&&n!==t)throw new Error(`CodeGen: wrong number of nodes: ${n} vs ${t} expected`);return this._nodes.length=r,this}func(t,r=Y.nil,n,a){return this._blockNode(new ca(t,r,n)),a&&this.code(a).endFunc(),this}endFunc(){return this._endBlockNode(ca)}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 en))throw new Error('CodeGen: "else" without "if"');return this._currNode=r.else=t,this}get _root(){return this._nodes[0]}get _currNode(){let t=this._nodes;return t[t.length-1]}set _currNode(t){let r=this._nodes;r[r.length-1]=t}};Z.CodeGen=Pd;function rn(e,t){for(let r in t)e[r]=(e[r]||0)+(t[r]||0);return e}o(rn,"addNames");function Ji(e,t){return t instanceof Y._CodeOrName?rn(e,t.names):e}o(Ji,"addExprNames");function Fn(e,t,r){if(e instanceof Y.Name)return n(e);if(!a(e))return e;return new Y._Code(e._items.reduce((i,s)=>(s instanceof Y.Name&&(s=n(s)),s instanceof Y._Code?i.push(...s._items):i.push(s),i),[]));function n(i){let s=r[i.str];return s===void 0||t[i.str]!==1?i:(delete t[i.str],s)}function a(i){return i instanceof Y._Code&&i._items.some(s=>s instanceof Y.Name&&t[s.str]===1&&r[s.str]!==void 0)}}o(Fn,"optimizeExpr");function Yx(e,t){for(let r in t)e[r]=(e[r]||0)-(t[r]||0)}o(Yx,"subtractNames");function Eg(e){return typeof e=="boolean"||typeof e=="number"||e===null?!e:(0,Y._)`!${xd(e)}`}o(Eg,"not");Z.not=Eg;var Qx=Ug(Z.operators.AND);function Xx(...e){return e.reduce(Qx)}o(Xx,"and");Z.and=Xx;var ek=Ug(Z.operators.OR);function tk(...e){return e.reduce(ek)}o(tk,"or");Z.or=tk;function Ug(e){return(t,r)=>t===Y.nil?r:r===Y.nil?t:(0,Y._)`${xd(t)} ${e} ${xd(r)}`}o(Ug,"mappend");function xd(e){return e instanceof Y.Name?e:(0,Y._)`(${e})`}o(xd,"par")});var te=k(J=>{"use strict";Object.defineProperty(J,"__esModule",{value:!0});J.checkStrictMode=J.getErrorPath=J.Type=J.useFunc=J.setEvaluated=J.evaluatedPropsToName=J.mergeEvaluated=J.eachItem=J.unescapeJsonPointer=J.escapeJsonPointer=J.escapeFragment=J.unescapeFragment=J.schemaRefOrVal=J.schemaHasRulesButRef=J.schemaHasRules=J.checkUnknownRules=J.alwaysValidSchema=J.toHash=void 0;var ie=F(),rk=ia();function nk(e){let t={};for(let r of e)t[r]=!0;return t}o(nk,"toHash");J.toHash=nk;function ok(e,t){return typeof t=="boolean"?t:Object.keys(t).length===0?!0:(Mg(e,t),!zg(t,e.self.RULES.all))}o(ok,"alwaysValidSchema");J.alwaysValidSchema=ok;function Mg(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]||jg(e,`unknown keyword: "${i}"`)}o(Mg,"checkUnknownRules");J.checkUnknownRules=Mg;function zg(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(t[r])return!0;return!1}o(zg,"schemaHasRules");J.schemaHasRules=zg;function ak(e,t){if(typeof e=="boolean")return!e;for(let r in e)if(r!=="$ref"&&t.all[r])return!0;return!1}o(ak,"schemaHasRulesButRef");J.schemaHasRulesButRef=ak;function ik({topSchemaRef:e,schemaPath:t},r,n,a){if(!a){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ie._)`${r}`}return(0,ie._)`${e}${t}${(0,ie.getProperty)(n)}`}o(ik,"schemaRefOrVal");J.schemaRefOrVal=ik;function sk(e){return qg(decodeURIComponent(e))}o(sk,"unescapeFragment");J.unescapeFragment=sk;function ck(e){return encodeURIComponent(Td(e))}o(ck,"escapeFragment");J.escapeFragment=ck;function Td(e){return typeof e=="number"?`${e}`:e.replace(/~/g,"~0").replace(/\//g,"~1")}o(Td,"escapeJsonPointer");J.escapeJsonPointer=Td;function qg(e){return e.replace(/~1/g,"/").replace(/~0/g,"~")}o(qg,"unescapeJsonPointer");J.unescapeJsonPointer=qg;function uk(e,t){if(Array.isArray(e))for(let r of e)t(r);else t(e)}o(uk,"eachItem");J.eachItem=uk;function Og({mergeNames:e,mergeToName:t,mergeValues:r,resultToName:n}){return(a,i,s,c)=>{let d=s===void 0?i:s instanceof ie.Name?(i instanceof ie.Name?e(a,i,s):t(a,i,s),s):i instanceof ie.Name?(t(a,s,i),i):r(i,s);return c===ie.Name&&!(d instanceof ie.Name)?n(a,d):d}}o(Og,"makeMergeEvaluated");J.mergeEvaluated={props:Og({mergeNames:o((e,t,r)=>e.if((0,ie._)`${r} !== true && ${t} !== undefined`,()=>{e.if((0,ie._)`${t} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,ie._)`${r} || {}`).code((0,ie._)`Object.assign(${r}, ${t})`))}),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,ie._)`${r} !== true`,()=>{t===!0?e.assign(r,!0):(e.assign(r,(0,ie._)`${r} || {}`),Ad(e,r,t))}),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:{...e,...t},"mergeValues"),resultToName:Ng}),items:Og({mergeNames:o((e,t,r)=>e.if((0,ie._)`${r} !== true && ${t} !== undefined`,()=>e.assign(r,(0,ie._)`${t} === true ? true : ${r} > ${t} ? ${r} : ${t}`)),"mergeNames"),mergeToName:o((e,t,r)=>e.if((0,ie._)`${r} !== true`,()=>e.assign(r,t===!0?!0:(0,ie._)`${r} > ${t} ? ${r} : ${t}`)),"mergeToName"),mergeValues:o((e,t)=>e===!0?!0:Math.max(e,t),"mergeValues"),resultToName:o((e,t)=>e.var("items",t),"resultToName")})};function Ng(e,t){if(t===!0)return e.var("props",!0);let r=e.var("props",(0,ie._)`{}`);return t!==void 0&&Ad(e,r,t),r}o(Ng,"evaluatedPropsToName");J.evaluatedPropsToName=Ng;function Ad(e,t,r){Object.keys(r).forEach(n=>e.assign((0,ie._)`${t}${(0,ie.getProperty)(n)}`,!0))}o(Ad,"setEvaluated");J.setEvaluated=Ad;var $g={};function dk(e,t){return e.scopeValue("func",{ref:t,code:$g[t.code]||($g[t.code]=new rk._Code(t.code))})}o(dk,"useFunc");J.useFunc=dk;var kd;(function(e){e[e.Num=0]="Num",e[e.Str=1]="Str"})(kd||(J.Type=kd={}));function lk(e,t,r){if(e instanceof ie.Name){let n=t===kd.Num;return r?n?(0,ie._)`"[" + ${e} + "]"`:(0,ie._)`"['" + ${e} + "']"`:n?(0,ie._)`"/" + ${e}`:(0,ie._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ie.getProperty)(e).toString():"/"+Td(e)}o(lk,"getErrorPath");J.getErrorPath=lk;function jg(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(jg,"checkStrictMode");J.checkStrictMode=jg});var Xt=k(Ed=>{"use strict";Object.defineProperty(Ed,"__esModule",{value:!0});var He=F(),pk={data:new He.Name("data"),valCxt:new He.Name("valCxt"),instancePath:new He.Name("instancePath"),parentData:new He.Name("parentData"),parentDataProperty:new He.Name("parentDataProperty"),rootData:new He.Name("rootData"),dynamicAnchors:new He.Name("dynamicAnchors"),vErrors:new He.Name("vErrors"),errors:new He.Name("errors"),this:new He.Name("this"),self:new He.Name("self"),scope:new He.Name("scope"),json:new He.Name("json"),jsonPos:new He.Name("jsonPos"),jsonLen:new He.Name("jsonLen"),jsonPart:new He.Name("jsonPart")};Ed.default=pk});var pa=k(Le=>{"use strict";Object.defineProperty(Le,"__esModule",{value:!0});Le.extendErrors=Le.resetErrorsCount=Le.reportExtraError=Le.reportError=Le.keyword$DataError=Le.keywordError=void 0;var Q=F(),Yi=te(),Ve=Xt();Le.keywordError={message:o(({keyword:e})=>(0,Q.str)`must pass "${e}" keyword validation`,"message")};Le.keyword$DataError={message:o(({keyword:e,schemaType:t})=>t?(0,Q.str)`"${e}" keyword must be ${t} ($data)`:(0,Q.str)`"${e}" keyword is invalid ($data)`,"message")};function mk(e,t=Le.keywordError,r,n){let{it:a}=e,{gen:i,compositeRule:s,allErrors:c}=a,d=Lg(e,t,r);n??(s||c)?Dg(i,d):Hg(a,(0,Q._)`[${d}]`)}o(mk,"reportError");Le.reportError=mk;function fk(e,t=Le.keywordError,r){let{it:n}=e,{gen:a,compositeRule:i,allErrors:s}=n,c=Lg(e,t,r);Dg(a,c),i||s||Hg(n,Ve.default.vErrors)}o(fk,"reportExtraError");Le.reportExtraError=fk;function hk(e,t){e.assign(Ve.default.errors,t),e.if((0,Q._)`${Ve.default.vErrors} !== null`,()=>e.if(t,()=>e.assign((0,Q._)`${Ve.default.vErrors}.length`,t),()=>e.assign(Ve.default.vErrors,null)))}o(hk,"resetErrorsCount");Le.resetErrorsCount=hk;function gk({gen:e,keyword:t,schemaValue:r,data:n,errsCount:a,it:i}){if(a===void 0)throw new Error("ajv implementation error");let s=e.name("err");e.forRange("i",a,Ve.default.errors,c=>{e.const(s,(0,Q._)`${Ve.default.vErrors}[${c}]`),e.if((0,Q._)`${s}.instancePath === undefined`,()=>e.assign((0,Q._)`${s}.instancePath`,(0,Q.strConcat)(Ve.default.instancePath,i.errorPath))),e.assign((0,Q._)`${s}.schemaPath`,(0,Q.str)`${i.errSchemaPath}/${t}`),i.opts.verbose&&(e.assign((0,Q._)`${s}.schema`,r),e.assign((0,Q._)`${s}.data`,n))})}o(gk,"extendErrors");Le.extendErrors=gk;function Dg(e,t){let r=e.const("err",t);e.if((0,Q._)`${Ve.default.vErrors} === null`,()=>e.assign(Ve.default.vErrors,(0,Q._)`[${r}]`),(0,Q._)`${Ve.default.vErrors}.push(${r})`),e.code((0,Q._)`${Ve.default.errors}++`)}o(Dg,"addError");function Hg(e,t){let{gen:r,validateName:n,schemaEnv:a}=e;a.$async?r.throw((0,Q._)`new ${e.ValidationError}(${t})`):(r.assign((0,Q._)`${n}.errors`,t),r.return(!1))}o(Hg,"returnErrors");var nn={keyword:new Q.Name("keyword"),schemaPath:new Q.Name("schemaPath"),params:new Q.Name("params"),propertyName:new Q.Name("propertyName"),message:new Q.Name("message"),schema:new Q.Name("schema"),parentSchema:new Q.Name("parentSchema")};function Lg(e,t,r){let{createErrors:n}=e.it;return n===!1?(0,Q._)`{}`:yk(e,t,r)}o(Lg,"errorObjectCode");function yk(e,t,r={}){let{gen:n,it:a}=e,i=[Sk(a,r),vk(e,r)];return _k(e,t,i),n.object(...i)}o(yk,"errorObject");function Sk({errorPath:e},{instancePath:t}){let r=t?(0,Q.str)`${e}${(0,Yi.getErrorPath)(t,Yi.Type.Str)}`:e;return[Ve.default.instancePath,(0,Q.strConcat)(Ve.default.instancePath,r)]}o(Sk,"errorInstancePath");function vk({keyword:e,it:{errSchemaPath:t}},{schemaPath:r,parentSchema:n}){let a=n?t:(0,Q.str)`${t}/${e}`;return r&&(a=(0,Q.str)`${a}${(0,Yi.getErrorPath)(r,Yi.Type.Str)}`),[nn.schemaPath,a]}o(vk,"errorSchemaPath");function _k(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([nn.keyword,a],[nn.params,typeof t=="function"?t(e):t||(0,Q._)`{}`]),d.messages&&n.push([nn.message,typeof r=="function"?r(e):r]),d.verbose&&n.push([nn.schema,s],[nn.parentSchema,(0,Q._)`${l}${m}`],[Ve.default.data,i]),p&&n.push([nn.propertyName,p])}o(_k,"extraErrorProps")});var Gg=k(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.boolOrEmptySchema=Zn.topBoolOrEmptySchema=void 0;var wk=pa(),bk=F(),Rk=Xt(),Ck={message:"boolean schema is false"};function Ik(e){let{gen:t,schema:r,validateName:n}=e;r===!1?Bg(e,!1):typeof r=="object"&&r.$async===!0?t.return(Rk.default.data):(t.assign((0,bk._)`${n}.errors`,null),t.return(!0))}o(Ik,"topBoolOrEmptySchema");Zn.topBoolOrEmptySchema=Ik;function Pk(e,t){let{gen:r,schema:n}=e;n===!1?(r.var(t,!1),Bg(e)):r.var(t,!0)}o(Pk,"boolOrEmptySchema");Zn.boolOrEmptySchema=Pk;function Bg(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,wk.reportError)(a,Ck,void 0,t)}o(Bg,"falseSchemaError")});var Ud=k(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.getRules=Kn.isJSONType=void 0;var xk=["string","number","integer","boolean","null","object","array"],kk=new Set(xk);function Tk(e){return typeof e=="string"&&kk.has(e)}o(Tk,"isJSONType");Kn.isJSONType=Tk;function Ak(){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(Ak,"getRules");Kn.getRules=Ak});var Od=k(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.shouldUseRule=Ir.shouldUseGroup=Ir.schemaHasRulesForType=void 0;function Ek({schema:e,self:t},r){let n=t.RULES.types[r];return n&&n!==!0&&Vg(e,n)}o(Ek,"schemaHasRulesForType");Ir.schemaHasRulesForType=Ek;function Vg(e,t){return t.rules.some(r=>Fg(e,r))}o(Vg,"shouldUseGroup");Ir.shouldUseGroup=Vg;function Fg(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(Fg,"shouldUseRule");Ir.shouldUseRule=Fg});var ma=k(Be=>{"use strict";Object.defineProperty(Be,"__esModule",{value:!0});Be.reportTypeError=Be.checkDataTypes=Be.checkDataType=Be.coerceAndCheckDataType=Be.getJSONTypes=Be.getSchemaTypes=Be.DataType=void 0;var Uk=Ud(),Ok=Od(),$k=pa(),G=F(),Zg=te(),Jn;(function(e){e[e.Correct=0]="Correct",e[e.Wrong=1]="Wrong"})(Jn||(Be.DataType=Jn={}));function Mk(e){let t=Kg(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(Mk,"getSchemaTypes");Be.getSchemaTypes=Mk;function Kg(e){let t=Array.isArray(e)?e:e?[e]:[];if(t.every(Uk.isJSONType))return t;throw new Error("type must be JSONType or JSONType[]: "+t.join(","))}o(Kg,"getJSONTypes");Be.getJSONTypes=Kg;function zk(e,t){let{gen:r,data:n,opts:a}=e,i=qk(t,a.coerceTypes),s=t.length>0&&!(i.length===0&&t.length===1&&(0,Ok.schemaHasRulesForType)(e,t[0]));if(s){let c=Md(t,n,a.strictNumbers,Jn.Wrong);r.if(c,()=>{i.length?Nk(e,t,i):zd(e)})}return s}o(zk,"coerceAndCheckDataType");Be.coerceAndCheckDataType=zk;var Jg=new Set(["string","number","integer","boolean","null"]);function qk(e,t){return t?e.filter(r=>Jg.has(r)||t==="array"&&r==="array"):[]}o(qk,"coerceToTypes");function Nk(e,t,r){let{gen:n,data:a,opts:i}=e,s=n.let("dataType",(0,G._)`typeof ${a}`),c=n.let("coerced",(0,G._)`undefined`);i.coerceTypes==="array"&&n.if((0,G._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>n.assign(a,(0,G._)`${a}[0]`).assign(s,(0,G._)`typeof ${a}`).if(Md(t,a,i.strictNumbers),()=>n.assign(c,a))),n.if((0,G._)`${c} !== undefined`);for(let p of r)(Jg.has(p)||p==="array"&&i.coerceTypes==="array")&&d(p);n.else(),zd(e),n.endIf(),n.if((0,G._)`${c} !== undefined`,()=>{n.assign(a,c),jk(e,c)});function d(p){switch(p){case"string":n.elseIf((0,G._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,G._)`"" + ${a}`).elseIf((0,G._)`${a} === null`).assign(c,(0,G._)`""`);return;case"number":n.elseIf((0,G._)`${s} == "boolean" || ${a} === null
|
|
27
27
|
|| (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,G._)`+${a}`);return;case"integer":n.elseIf((0,G._)`${s} === "boolean" || ${a} === null
|
|
28
28
|
|| (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,G._)`+${a}`);return;case"boolean":n.elseIf((0,G._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,G._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case"null":n.elseIf((0,G._)`${a} === "" || ${a} === 0 || ${a} === false`),n.assign(c,null);return;case"array":n.elseIf((0,G._)`${s} === "string" || ${s} === "number"
|
|
29
|
-
|| ${s} === "boolean" || ${a} === null`).assign(c,(0,G._)`[${a}]`)}}o(d,"coerceSpecificType")}o(Ek,"coerceData");function Uk({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,G._)`${t} !== undefined`,()=>e.assign((0,G._)`${t}[${r}]`,n))}o(Uk,"assignParentData");function $d(e,t,r,n=Fn.Correct){let a=n===Fn.Correct?G.operators.EQ:G.operators.NEQ,i;switch(e){case"null":return(0,G._)`${t} ${a} null`;case"array":i=(0,G._)`Array.isArray(${t})`;break;case"object":i=(0,G._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,G._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,G._)`typeof ${t} ${a} ${e}`}return n===Fn.Correct?i:(0,G.not)(i);function s(c=G.nil){return(0,G.and)((0,G._)`typeof ${t} == "number"`,c,r?(0,G._)`isFinite(${t})`:G.nil)}}o($d,"checkDataType");Le.checkDataType=$d;function zd(e,t,r,n){if(e.length===1)return $d(e[0],t,r,n);let a,i=(0,qg.toHash)(e);if(i.array&&i.object){let s=(0,G._)`typeof ${t} != "object"`;a=i.null?s:(0,G._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else a=G.nil;i.number&&delete i.integer;for(let s in i)a=(0,G.and)(a,$d(s,t,r,n));return a}o(zd,"checkDataTypes");Le.checkDataTypes=zd;var Ok={message:o(({schema:e})=>`must be ${e}`,"message"),params:o(({schema:e,schemaValue:t})=>typeof e=="string"?(0,G._)`{type: ${e}}`:(0,G._)`{type: ${t}}`,"params")};function Md(e){let t=$k(e);(0,xk.reportError)(t,Ok)}o(Md,"reportTypeError");Le.reportTypeError=Md;function $k(e){let{gen:t,data:r,schema:n}=e,a=(0,qg.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:a,schemaValue:a,parentSchema:n,params:{},it:e}}o($k,"getTypeErrorContext")});var Hg=k(Ji=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});Ji.assignDefaults=void 0;var Zn=F(),zk=te();function Mk(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let a in r)jg(e,a,r[a].default);else t==="array"&&Array.isArray(n)&&n.forEach((a,i)=>jg(e,i,a.default))}o(Mk,"assignDefaults");Ji.assignDefaults=Mk;function jg(e,t,r){let{gen:n,compositeRule:a,data:i,opts:s}=e;if(r===void 0)return;let c=(0,Zn._)`${i}${(0,Zn.getProperty)(t)}`;if(a){(0,zk.checkStrictMode)(e,`default is ignored for: ${c}`);return}let d=(0,Zn._)`${c} === undefined`;s.useDefaults==="empty"&&(d=(0,Zn._)`${d} || ${c} === null || ${c} === ""`),n.if(d,(0,Zn._)`${c} = ${(0,Zn.stringify)(r)}`)}o(jg,"assignDefault")});var pt=k(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.validateUnion=ne.validateArray=ne.usePattern=ne.callValidateCode=ne.schemaProperties=ne.allSchemaProperties=ne.noPropertyInData=ne.propertyInData=ne.isOwnProperty=ne.hasPropFunc=ne.reportMissingProp=ne.checkMissingProp=ne.checkReportMissingProp=void 0;var pe=F(),qd=te(),_r=Wt(),qk=te();function Nk(e,t){let{gen:r,data:n,it:a}=e;r.if(Dd(r,n,t,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,pe._)`${t}`},!0),e.error()})}o(Nk,"checkReportMissingProp");ne.checkReportMissingProp=Nk;function Dk({gen:e,data:t,it:{opts:r}},n,a){return(0,pe.or)(...n.map(i=>(0,pe.and)(Dd(e,t,i,r.ownProperties),(0,pe._)`${a} = ${i}`)))}o(Dk,"checkMissingProp");ne.checkMissingProp=Dk;function jk(e,t){e.setParams({missingProperty:t},!0),e.error()}o(jk,"reportMissingProp");ne.reportMissingProp=jk;function Lg(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,pe._)`Object.prototype.hasOwnProperty`})}o(Lg,"hasPropFunc");ne.hasPropFunc=Lg;function Nd(e,t,r){return(0,pe._)`${Lg(e)}.call(${t}, ${r})`}o(Nd,"isOwnProperty");ne.isOwnProperty=Nd;function Hk(e,t,r,n){let a=(0,pe._)`${t}${(0,pe.getProperty)(r)} !== undefined`;return n?(0,pe._)`${a} && ${Nd(e,t,r)}`:a}o(Hk,"propertyInData");ne.propertyInData=Hk;function Dd(e,t,r,n){let a=(0,pe._)`${t}${(0,pe.getProperty)(r)} === undefined`;return n?(0,pe.or)(a,(0,pe.not)(Nd(e,t,r))):a}o(Dd,"noPropertyInData");ne.noPropertyInData=Dd;function Bg(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}o(Bg,"allSchemaProperties");ne.allSchemaProperties=Bg;function Lk(e,t){return Bg(t).filter(r=>!(0,qd.alwaysValidSchema)(e,t[r]))}o(Lk,"schemaProperties");ne.schemaProperties=Lk;function Bk({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:a,errorPath:i},it:s},c,d,p){let l=p?(0,pe._)`${e}, ${t}, ${n}${a}`:t,m=[[_r.default.instancePath,(0,pe.strConcat)(_r.default.instancePath,i)],[_r.default.parentData,s.parentData],[_r.default.parentDataProperty,s.parentDataProperty],[_r.default.rootData,_r.default.rootData]];s.opts.dynamicRef&&m.push([_r.default.dynamicAnchors,_r.default.dynamicAnchors]);let h=(0,pe._)`${l}, ${r.object(...m)}`;return d!==pe.nil?(0,pe._)`${c}.call(${d}, ${h})`:(0,pe._)`${c}(${h})`}o(Bk,"callValidateCode");ne.callValidateCode=Bk;var Gk=(0,pe._)`new RegExp`;function Vk({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:a}=t.code,i=a(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,pe._)`${a.code==="new RegExp"?Gk:(0,qk.useFunc)(e,a)}(${r}, ${n})`})}o(Vk,"usePattern");ne.usePattern=Vk;function Fk(e){let{gen:t,data:r,keyword:n,it:a}=e,i=t.name("valid");if(a.allErrors){let c=t.let("valid",!0);return s(()=>t.assign(c,!1)),c}return t.var(i,!0),s(()=>t.break()),i;function s(c){let d=t.const("len",(0,pe._)`${r}.length`);t.forRange("i",0,d,p=>{e.subschema({keyword:n,dataProp:p,dataPropType:qd.Type.Num},i),t.if((0,pe.not)(i),c)})}o(s,"validateItems")}o(Fk,"validateArray");ne.validateArray=Fk;function Zk(e){let{gen:t,schema:r,keyword:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(d=>(0,qd.alwaysValidSchema)(a,d))&&!a.opts.unevaluated)return;let s=t.let("valid",!1),c=t.name("_valid");t.block(()=>r.forEach((d,p)=>{let l=e.subschema({keyword:n,schemaProp:p,compositeRule:!0},c);t.assign(s,(0,pe._)`${s} || ${c}`),e.mergeValidEvaluated(l,c)||t.if((0,pe.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}o(Zk,"validateUnion");ne.validateUnion=Zk});var Fg=k(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.validateKeywordUsage=kt.validSchemaType=kt.funcKeywordCode=kt.macroKeywordCode=void 0;var Fe=F(),en=Wt(),Kk=pt(),Jk=da();function Wk(e,t){let{gen:r,keyword:n,schema:a,parentSchema:i,it:s}=e,c=t.macro.call(s.self,a,i,s),d=Vg(r,n,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let p=r.name("valid");e.subschema({schema:c,schemaPath:Fe.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:d,compositeRule:!0},p),e.pass(p,()=>e.error(!0))}o(Wk,"macroKeywordCode");kt.macroKeywordCode=Wk;function Yk(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=Vg(n,a,p),m=n.let("valid");e.block$data(m,h),e.ok((r=t.valid)!==null&&r!==void 0?r:m);function h(){if(t.errors===!1)S(),t.modifying&&Gg(e),_(()=>e.error());else{let w=t.async?y():v();t.modifying&&Gg(e),_(()=>Qk(e,w))}}o(h,"validateKeyword");function y(){let w=n.let("ruleErrs",null);return n.try(()=>S((0,Fe._)`await `),b=>n.assign(m,!1).if((0,Fe._)`${b} instanceof ${d.ValidationError}`,()=>n.assign(w,(0,Fe._)`${b}.errors`),()=>n.throw(b))),w}o(y,"validateAsync");function v(){let w=(0,Fe._)`${l}.errors`;return n.assign(w,null),S(Fe.nil),w}o(v,"validateSync");function S(w=t.async?(0,Fe._)`await `:Fe.nil){let b=d.opts.passContext?en.default.this:en.default.self,R=!("compile"in t&&!c||t.schema===!1);n.assign(m,(0,Fe._)`${w}${(0,Kk.callValidateCode)(e,l,b,R)}`,t.modifying)}o(S,"assignValid");function _(w){var b;n.if((0,Fe.not)((b=t.valid)!==null&&b!==void 0?b:m),w)}o(_,"reportErrs")}o(Yk,"funcKeywordCode");kt.funcKeywordCode=Yk;function Gg(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Fe._)`${n.parentData}[${n.parentDataProperty}]`))}o(Gg,"modifyData");function Qk(e,t){let{gen:r}=e;r.if((0,Fe._)`Array.isArray(${t})`,()=>{r.assign(en.default.vErrors,(0,Fe._)`${en.default.vErrors} === null ? ${t} : ${en.default.vErrors}.concat(${t})`).assign(en.default.errors,(0,Fe._)`${en.default.vErrors}.length`),(0,Jk.extendErrors)(e)},()=>e.error())}o(Qk,"addErrs");function Xk({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}o(Xk,"checkAsyncKeyword");function Vg(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Fe.stringify)(r)})}o(Vg,"useKeyword");function eT(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(eT,"validSchemaType");kt.validSchemaType=eT;function tT({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(tT,"validateKeywordUsage");kt.validateKeywordUsage=tT});var Kg=k(wr=>{"use strict";Object.defineProperty(wr,"__esModule",{value:!0});wr.extendSubschemaMode=wr.extendSubschemaData=wr.getSubschema=void 0;var Tt=F(),Zg=te();function rT(e,{keyword:t,schemaProp:r,schema:n,schemaPath:a,errSchemaPath:i,topSchemaRef:s}){if(t!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(t!==void 0){let c=e.schema[t];return r===void 0?{schema:c,schemaPath:(0,Tt._)`${e.schemaPath}${(0,Tt.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:c[r],schemaPath:(0,Tt._)`${e.schemaPath}${(0,Tt.getProperty)(t)}${(0,Tt.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,Zg.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(rT,"getSubschema");wr.getSubschema=rT;function nT(e,t,{dataProp:r,dataPropType:n,data:a,dataTypes:i,propertyName:s}){if(a!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:c}=t;if(r!==void 0){let{errorPath:p,dataPathArr:l,opts:m}=t,h=c.let("data",(0,Tt._)`${t.data}${(0,Tt.getProperty)(r)}`,!0);d(h),e.errorPath=(0,Tt.str)`${p}${(0,Zg.getErrorPath)(r,n,m.jsPropertySyntax)}`,e.parentDataProperty=(0,Tt._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(a!==void 0){let p=a instanceof Tt.Name?a:c.let("data",a,!0);d(p),s!==void 0&&(e.propertyName=s)}i&&(e.dataTypes=i);function d(p){e.data=p,e.dataLevel=t.dataLevel+1,e.dataTypes=[],t.definedProperties=new Set,e.parentData=t.data,e.dataNames=[...t.dataNames,p]}o(d,"dataContextProps")}o(nT,"extendSubschemaData");wr.extendSubschemaData=nT;function oT(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(oT,"extendSubschemaMode");wr.extendSubschemaMode=oT});var jd=k((J4,Jg)=>{"use strict";Jg.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 Yg=k((Y4,Wg)=>{"use strict";var br=Wg.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(){};Wi(t,n,a,e,"",e)};br.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};br.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};br.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};br.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 Wi(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 br.arrayKeywords)for(var h=0;h<m.length;h++)Wi(e,t,r,m[h],a+"/"+l+"/"+h,i,a,l,n,h)}else if(l in br.propsKeywords){if(m&&typeof m=="object")for(var y in m)Wi(e,t,r,m[y],a+"/"+l+"/"+aT(y),i,a,l,n,y)}else(l in br.keywords||e.allKeys&&!(l in br.skipKeywords))&&Wi(e,t,r,m,a+"/"+l,i,a,l,n)}r(n,a,i,s,c,d,p)}}o(Wi,"_traverse");function aT(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(aT,"escapeJsonPtr")});var pa=k(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.getSchemaRefs=et.resolveUrl=et.normalizeId=et._getFullPath=et.getFullPath=et.inlineRef=void 0;var iT=te(),sT=jd(),cT=Yg(),uT=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function dT(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Hd(e):t?Qg(e)<=t:!1}o(dT,"inlineRef");et.inlineRef=dT;var lT=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Hd(e){for(let t in e){if(lT.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Hd)||typeof r=="object"&&Hd(r))return!0}return!1}o(Hd,"hasRef");function Qg(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!uT.has(r)&&(typeof e[r]=="object"&&(0,iT.eachItem)(e[r],n=>t+=Qg(n)),t===1/0))return 1/0}return t}o(Qg,"countKeys");function Xg(e,t="",r){r!==!1&&(t=Kn(t));let n=e.parse(t);return ey(e,n)}o(Xg,"getFullPath");et.getFullPath=Xg;function ey(e,t){return e.serialize(t).split("#")[0]+"#"}o(ey,"_getFullPath");et._getFullPath=ey;var pT=/#\/?$/;function Kn(e){return e?e.replace(pT,""):""}o(Kn,"normalizeId");et.normalizeId=Kn;function mT(e,t,r){return r=Kn(r),e.resolve(t,r)}o(mT,"resolveUrl");et.resolveUrl=mT;var fT=/^[a-z_][-a-z0-9._]*$/i;function hT(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,a=Kn(e[r]||t),i={"":a},s=Xg(n,a,!1),c={},d=new Set;return cT(e,{allKeys:!0},(m,h,y,v)=>{if(v===void 0)return;let S=s+h,_=i[v];typeof m[r]=="string"&&(_=w.call(this,m[r])),b.call(this,m.$anchor),b.call(this,m.$dynamicAnchor),i[h]=_;function w(R){let z=this.opts.uriResolver.resolve;if(R=Kn(_?z(_,R):R),d.has(R))throw l(R);d.add(R);let M=this.refs[R];return typeof M=="string"&&(M=this.refs[M]),typeof M=="object"?p(m,M.schema,R):R!==Kn(S)&&(R[0]==="#"?(p(m,c[R],R),c[R]=m):this.refs[R]=S),R}o(w,"addRef");function b(R){if(typeof R=="string"){if(!fT.test(R))throw new Error(`invalid anchor "${R}"`);w.call(this,`#${R}`)}}o(b,"addAnchor")}),c;function p(m,h,y){if(h!==void 0&&!sT(m,h))throw l(y)}o(p,"checkAmbiguosRef");function l(m){return new Error(`reference "${m}" resolves to more than one schema`)}o(l,"ambiguos")}o(hT,"getSchemaRefs");et.getSchemaRefs=hT});var ha=k(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.getData=Rr.KeywordCxt=Rr.validateFunctionCode=void 0;var ay=$g(),ty=la(),Bd=Od(),Yi=la(),gT=Hg(),fa=Fg(),Ld=Kg(),O=F(),j=Wt(),yT=pa(),Yt=te(),ma=da();function ST(e){if(cy(e)&&(uy(e),sy(e))){wT(e);return}iy(e,()=>(0,ay.topBoolOrEmptySchema)(e))}o(ST,"validateFunctionCode");Rr.validateFunctionCode=ST;function iy({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},i){a.code.es5?e.func(t,(0,O._)`${j.default.data}, ${j.default.valCxt}`,n.$async,()=>{e.code((0,O._)`"use strict"; ${ry(r,a)}`),_T(e,a),e.code(i)}):e.func(t,(0,O._)`${j.default.data}, ${vT(a)}`,n.$async,()=>e.code(ry(r,a)).code(i))}o(iy,"validateFunction");function vT(e){return(0,O._)`{${j.default.instancePath}="", ${j.default.parentData}, ${j.default.parentDataProperty}, ${j.default.rootData}=${j.default.data}${e.dynamicRef?(0,O._)`, ${j.default.dynamicAnchors}={}`:O.nil}}={}`}o(vT,"destructureValCxt");function _T(e,t){e.if(j.default.valCxt,()=>{e.var(j.default.instancePath,(0,O._)`${j.default.valCxt}.${j.default.instancePath}`),e.var(j.default.parentData,(0,O._)`${j.default.valCxt}.${j.default.parentData}`),e.var(j.default.parentDataProperty,(0,O._)`${j.default.valCxt}.${j.default.parentDataProperty}`),e.var(j.default.rootData,(0,O._)`${j.default.valCxt}.${j.default.rootData}`),t.dynamicRef&&e.var(j.default.dynamicAnchors,(0,O._)`${j.default.valCxt}.${j.default.dynamicAnchors}`)},()=>{e.var(j.default.instancePath,(0,O._)`""`),e.var(j.default.parentData,(0,O._)`undefined`),e.var(j.default.parentDataProperty,(0,O._)`undefined`),e.var(j.default.rootData,j.default.data),t.dynamicRef&&e.var(j.default.dynamicAnchors,(0,O._)`{}`)})}o(_T,"destructureValCxtES5");function wT(e){let{schema:t,opts:r,gen:n}=e;iy(e,()=>{r.$comment&&t.$comment&&ly(e),PT(e),n.let(j.default.vErrors,null),n.let(j.default.errors,0),r.unevaluated&&bT(e),dy(e),TT(e)})}o(wT,"topSchemaObjCode");function bT(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,O._)`${r}.evaluated`),t.if((0,O._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,O._)`${e.evaluated}.props`,(0,O._)`undefined`)),t.if((0,O._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,O._)`${e.evaluated}.items`,(0,O._)`undefined`))}o(bT,"resetEvaluated");function ry(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,O._)`/*# sourceURL=${r} */`:O.nil}o(ry,"funcSourceUrl");function RT(e,t){if(cy(e)&&(uy(e),sy(e))){CT(e,t);return}(0,ay.boolOrEmptySchema)(e,t)}o(RT,"subschemaCode");function sy({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(sy,"schemaCxtHasRules");function cy(e){return typeof e.schema!="boolean"}o(cy,"isSchemaObj");function CT(e,t){let{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&ly(e),xT(e),kT(e);let i=n.const("_errs",j.default.errors);dy(e,i),n.var(t,(0,O._)`${i} === ${j.default.errors}`)}o(CT,"subSchemaObjCode");function uy(e){(0,Yt.checkUnknownRules)(e),IT(e)}o(uy,"checkKeywords");function dy(e,t){if(e.opts.jtd)return ny(e,[],!1,t);let r=(0,ty.getSchemaTypes)(e.schema),n=(0,ty.coerceAndCheckDataType)(e,r);ny(e,r,!n,t)}o(dy,"typeAndKeywords");function IT(e){let{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,Yt.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}o(IT,"checkRefsAndKeywords");function PT(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Yt.checkStrictMode)(e,"default is ignored in the schema root")}o(PT,"checkNoDefault");function xT(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,yT.resolveUrl)(e.opts.uriResolver,e.baseId,t))}o(xT,"updateContext");function kT(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}o(kT,"checkAsyncSchema");function ly({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){let i=r.$comment;if(a.$comment===!0)e.code((0,O._)`${j.default.self}.logger.log(${i})`);else if(typeof a.$comment=="function"){let s=(0,O.str)`${n}/$comment`,c=e.scopeValue("root",{ref:t.root});e.code((0,O._)`${j.default.self}.opts.$comment(${i}, ${s}, ${c}.schema)`)}}o(ly,"commentKeyword");function TT(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:i}=e;r.$async?t.if((0,O._)`${j.default.errors} === 0`,()=>t.return(j.default.data),()=>t.throw((0,O._)`new ${a}(${j.default.vErrors})`)):(t.assign((0,O._)`${n}.errors`,j.default.vErrors),i.unevaluated&&AT(e),t.return((0,O._)`${j.default.errors} === 0`))}o(TT,"returnResults");function AT({gen:e,evaluated:t,props:r,items:n}){r instanceof O.Name&&e.assign((0,O._)`${t}.props`,r),n instanceof O.Name&&e.assign((0,O._)`${t}.items`,n)}o(AT,"assignEvaluated");function ny(e,t,r,n){let{gen:a,schema:i,data:s,allErrors:c,opts:d,self:p}=e,{RULES:l}=p;if(i.$ref&&(d.ignoreKeywordsWithRef||!(0,Yt.schemaHasRulesButRef)(i,l))){a.block(()=>my(e,"$ref",l.all.$ref.definition));return}d.jtd||ET(e,t),a.block(()=>{for(let h of l.rules)m(h);m(l.post)});function m(h){(0,Bd.shouldUseGroup)(i,h)&&(h.type?(a.if((0,Yi.checkDataType)(h.type,s,d.strictNumbers)),oy(e,h),t.length===1&&t[0]===h.type&&r&&(a.else(),(0,Yi.reportTypeError)(e)),a.endIf()):oy(e,h),c||a.if((0,O._)`${j.default.errors} === ${n||0}`))}o(m,"groupKeywords")}o(ny,"schemaKeywords");function oy(e,t){let{gen:r,schema:n,opts:{useDefaults:a}}=e;a&&(0,gT.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,Bd.shouldUseRule)(n,i)&&my(e,i.keyword,i.definition,t.type)})}o(oy,"iterateKeywords");function ET(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(UT(e,t),e.opts.allowUnionTypes||OT(e,t),$T(e,e.dataTypes))}o(ET,"checkStrictTypes");function UT(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{py(e.dataTypes,r)||Gd(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),MT(e,t)}}o(UT,"checkContextTypes");function OT(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Gd(e,"use allowUnionTypes to allow union type keyword")}o(OT,"checkMultipleTypes");function $T(e,t){let r=e.self.RULES.all;for(let n in r){let a=r[n];if(typeof a=="object"&&(0,Bd.shouldUseRule)(e.schema,a)){let{type:i}=a.definition;i.length&&!i.some(s=>zT(t,s))&&Gd(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}o($T,"checkKeywordTypes");function zT(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}o(zT,"hasApplicableType");function py(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}o(py,"includesType");function MT(e,t){let r=[];for(let n of e.dataTypes)py(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}o(MT,"narrowSchemaTypes");function Gd(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,Yt.checkStrictMode)(e,t,e.opts.strictTypes)}o(Gd,"strictTypesError");var Qi=class{static{o(this,"KeywordCxt")}constructor(t,r,n){if((0,fa.validateKeywordUsage)(t,r,n),this.gen=t.gen,this.allErrors=t.allErrors,this.keyword=n,this.data=t.data,this.schema=t.schema[n],this.$data=r.$data&&t.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,Yt.schemaRefOrVal)(t,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=t.schema,this.params={},this.it=t,this.def=r,this.$data)this.schemaCode=t.gen.const("vSchema",fy(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,fa.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",j.default.errors))}result(t,r,n){this.failResult((0,O.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,O.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,O._)`${r} !== undefined && (${(0,O.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?ma.reportExtraError:ma.reportError)(this,this.def.error,r)}$dataError(){(0,ma.reportError)(this,this.def.$dataError||ma.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ma.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=O.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=O.nil,r=O.nil){if(!this.$data)return;let{gen:n,schemaCode:a,schemaType:i,def:s}=this;n.if((0,O.or)((0,O._)`${a} === undefined`,r)),t!==O.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==O.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:a,it:i}=this;return(0,O.or)(s(),c());function s(){if(n.length){if(!(r instanceof O.Name))throw new Error("ajv implementation error");let d=Array.isArray(n)?n:[n];return(0,O._)`${(0,Yi.checkDataTypes)(d,r,i.opts.strictNumbers,Yi.DataType.Wrong)}`}return O.nil}function c(){if(a.validateSchema){let d=t.scopeValue("validate$data",{ref:a.validateSchema});return(0,O._)`!${d}(${r})`}return O.nil}}subschema(t,r){let n=(0,Ld.getSubschema)(this.it,t);(0,Ld.extendSubschemaData)(n,this.it,t),(0,Ld.extendSubschemaMode)(n,t);let a={...this.it,...n,items:void 0,props:void 0};return RT(a,r),a}mergeEvaluated(t,r){let{it:n,gen:a}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=Yt.mergeEvaluated.props(a,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=Yt.mergeEvaluated.items(a,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:a}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return a.if(r,()=>this.mergeEvaluated(t,O.Name)),!0}};Rr.KeywordCxt=Qi;function my(e,t,r,n){let a=new Qi(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0,fa.funcKeywordCode)(a,r):"macro"in r?(0,fa.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,fa.funcKeywordCode)(a,r)}o(my,"keywordCode");var qT=/^\/(?:[^~]|~0|~1)*$/,NT=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function fy(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,i;if(e==="")return j.default.rootData;if(e[0]==="/"){if(!qT.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,i=j.default.rootData}else{let p=NT.exec(e);if(!p)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+p[1];if(a=p[2],a==="#"){if(l>=t)throw new Error(d("property/index",l));return n[t-l]}if(l>t)throw new Error(d("data",l));if(i=r[t-l],!a)return i}let s=i,c=a.split("/");for(let p of c)p&&(i=(0,O._)`${i}${(0,O.getProperty)((0,Yt.unescapeJsonPointer)(p))}`,s=(0,O._)`${s} && ${i}`);return s;function d(p,l){return`Cannot access ${p} ${l} levels up, current level is ${t}`}}o(fy,"getData");Rr.getData=fy});var Xi=k(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var Vd=class extends Error{static{o(this,"ValidationError")}constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Fd.default=Vd});var ga=k(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var Zd=pa(),Kd=class extends Error{static{o(this,"MissingRefError")}constructor(t,r,n,a){super(a||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Zd.resolveUrl)(t,r,n),this.missingSchema=(0,Zd.normalizeId)((0,Zd.getFullPath)(t,this.missingRef))}};Jd.default=Kd});var ts=k(mt=>{"use strict";Object.defineProperty(mt,"__esModule",{value:!0});mt.resolveSchema=mt.getCompilingSchema=mt.resolveRef=mt.compileSchema=mt.SchemaEnv=void 0;var vt=F(),DT=Xi(),tn=Wt(),_t=pa(),hy=te(),jT=ha(),Jn=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,_t.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};mt.SchemaEnv=Jn;function Yd(e){let t=gy.call(this,e);if(t)return t;let r=(0,_t.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:a}=this.opts.code,{ownProperties:i}=this.opts,s=new vt.CodeGen(this.scope,{es5:n,lines:a,ownProperties:i}),c;e.$async&&(c=s.scopeValue("Error",{ref:DT.default,code:(0,vt._)`require("ajv/dist/runtime/validation_error").default`}));let d=s.scopeName("validate");e.validateName=d;let p={gen:s,allErrors:this.opts.allErrors,data:tn.default.data,parentData:tn.default.parentData,parentDataProperty:tn.default.parentDataProperty,dataNames:[tn.default.data],dataPathArr:[vt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,vt.stringify)(e.schema)}:{ref:e.schema}),validateName:d,ValidationError:c,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:vt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,vt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,jT.validateFunctionCode)(p),s.optimize(this.opts.code.optimize);let m=s.toString();l=`${s.scopeRefs(tn.default.scope)}return ${m}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let y=new Function(`${tn.default.self}`,`${tn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(d,{ref:y}),y.errors=null,y.schema=e.schema,y.schemaEnv=e,e.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:d,validateCode:m,scopeValues:s._values}),this.opts.unevaluated){let{props:v,items:S}=p;y.evaluated={props:v instanceof vt.Name?void 0:v,items:S instanceof vt.Name?void 0:S,dynamicProps:v instanceof vt.Name,dynamicItems:S instanceof vt.Name},y.source&&(y.source.evaluated=(0,vt.stringify)(y.evaluated))}return e.validate=y,e}catch(m){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),m}finally{this._compilations.delete(e)}}o(Yd,"compileSchema");mt.compileSchema=Yd;function HT(e,t,r){var n;r=(0,_t.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let i=GT.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 Jn({schema:s,schemaId:c,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=LT.call(this,i)}o(HT,"resolveRef");mt.resolveRef=HT;function LT(e){return(0,_t.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Yd.call(this,e)}o(LT,"inlineOrCompile");function gy(e){for(let t of this._compilations)if(BT(t,e))return t}o(gy,"getCompilingSchema");mt.getCompilingSchema=gy;function BT(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}o(BT,"sameSchemaEnv");function GT(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||es.call(this,e,t)}o(GT,"resolve");function es(e,t){let r=this.opts.uriResolver.parse(t),n=(0,_t._getFullPath)(this.opts.uriResolver,r),a=(0,_t.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===a)return Wd.call(this,r,e);let i=(0,_t.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let c=es.call(this,e,s);return typeof c?.schema!="object"?void 0:Wd.call(this,r,c)}if(typeof s?.schema=="object"){if(s.validate||Yd.call(this,s),i===(0,_t.normalizeId)(t)){let{schema:c}=s,{schemaId:d}=this.opts,p=c[d];return p&&(a=(0,_t.resolveUrl)(this.opts.uriResolver,a,p)),new Jn({schema:c,schemaId:d,root:e,baseId:a})}return Wd.call(this,r,s)}}o(es,"resolveSchema");mt.resolveSchema=es;var VT=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Wd(e,{baseId:t,schema:r,root:n}){var a;if(((a=e.fragment)===null||a===void 0?void 0:a[0])!=="/")return;for(let c of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let d=r[(0,hy.unescapeFragment)(c)];if(d===void 0)return;r=d;let p=typeof r=="object"&&r[this.opts.schemaId];!VT.has(c)&&p&&(t=(0,_t.resolveUrl)(this.opts.uriResolver,t,p))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,hy.schemaHasRulesButRef)(r,this.RULES)){let c=(0,_t.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=es.call(this,n,c)}let{schemaId:s}=this.opts;if(i=i||new Jn({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}o(Wd,"getJsonPointer")});var yy=k((u9,FT)=>{FT.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Xd=k((d9,wy)=>{"use strict";var ZT=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),vy=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Qd(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}o(Qd,"stringArrayToHexStripped");var KT=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Sy(e){return e.length=0,!0}o(Sy,"consumeIsZone");function JT(e,t,r){if(e.length){let n=Qd(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}o(JT,"consumeHextets");function WT(e){let t=0,r={error:!1,address:"",zone:""},n=[],a=[],i=!1,s=!1,c=JT;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=Sy}else{a.push(p);continue}}return a.length&&(c===Sy?r.zone=a.join(""):s?n.push(a.join("")):n.push(Qd(a))),r.address=n.join(""),r}o(WT,"getIPV6");function _y(e){if(YT(e,":")<2)return{host:e,isIPV6:!1};let t=WT(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(_y,"normalizeIPv6");function YT(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}o(YT,"findToken");function QT(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(QT,"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 eA(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!vy(r)){let n=_y(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(eA,"recomposeAuthority");wy.exports={nonSimpleDomain:KT,recomposeAuthority:eA,normalizeComponentEncoding:XT,removeDotSegments:QT,isIPv4:vy,isUUID:ZT,normalizeIPv6:_y,stringArrayToHexStripped:Qd}});var Py=k((p9,Iy)=>{"use strict";var{isUUID:tA}=Xd(),rA=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,nA=["http","https","ws","wss","urn","urn:uuid"];function oA(e){return nA.indexOf(e)!==-1}o(oA,"isValidSchemeName");function el(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}o(el,"wsIsSecure");function by(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}o(by,"httpParse");function Ry(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(Ry,"httpSerialize");function aA(e){return e.secure=el(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}o(aA,"wsParse");function iA(e){if((e.port===(el(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}o(iA,"wsSerialize");function sA(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(rA);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let a=`${n}:${t.nid||e.nid}`,i=tl(a);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}o(sA,"urnParse");function cA(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),a=`${r}:${t.nid||n}`,i=tl(a);i&&(e=i.serialize(e,t));let s=e,c=e.nss;return s.path=`${n||t.nid}:${c}`,t.skipEscape=!0,s}o(cA,"urnSerialize");function uA(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!tA(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}o(uA,"urnuuidParse");function dA(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}o(dA,"urnuuidSerialize");var Cy={scheme:"http",domainHost:!0,parse:by,serialize:Ry},lA={scheme:"https",domainHost:Cy.domainHost,parse:by,serialize:Ry},rs={scheme:"ws",domainHost:!0,parse:aA,serialize:iA},pA={scheme:"wss",domainHost:rs.domainHost,parse:rs.parse,serialize:rs.serialize},mA={scheme:"urn",parse:sA,serialize:cA,skipNormalize:!0},fA={scheme:"urn:uuid",parse:uA,serialize:dA,skipNormalize:!0},ns={http:Cy,https:lA,ws:rs,wss:pA,urn:mA,"urn:uuid":fA};Object.setPrototypeOf(ns,null);function tl(e){return e&&(ns[e]||ns[e.toLowerCase()])||void 0}o(tl,"getSchemeHandler");Iy.exports={wsIsSecure:el,SCHEMES:ns,isValidSchemeName:oA,getSchemeHandler:tl}});var Ty=k((f9,as)=>{"use strict";var{normalizeIPv6:hA,removeDotSegments:ya,recomposeAuthority:gA,normalizeComponentEncoding:os,isIPv4:yA,nonSimpleDomain:SA}=Xd(),{SCHEMES:vA,getSchemeHandler:xy}=Py();function _A(e,t){return typeof e=="string"?e=At(Qt(e,t),t):typeof e=="object"&&(e=Qt(At(e,t),t)),e}o(_A,"normalize");function wA(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},a=ky(Qt(e,n),Qt(t,n),n,!0);return n.skipEscape=!0,At(a,n)}o(wA,"resolve");function ky(e,t,r,n){let a={};return n||(e=Qt(At(e,r),r),t=Qt(At(t,r),r)),r=r||{},!r.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=ya(t.path||""),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=ya(t.path||""),a.query=t.query):(t.path?(t.path[0]==="/"?a.path=ya(t.path):((e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?a.path="/"+t.path:e.path?a.path=e.path.slice(0,e.path.lastIndexOf("/")+1)+t.path:a.path=t.path,a.path=ya(a.path)),a.query=t.query):(a.path=e.path,t.query!==void 0?a.query=t.query:a.query=e.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}o(ky,"resolveComponent");function bA(e,t,r){return typeof e=="string"?(e=unescape(e),e=At(os(Qt(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=At(os(e,!0),{...r,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=At(os(Qt(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=At(os(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}o(bA,"equal");function At(e,t){let r={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:""},n=Object.assign({},t),a=[],i=xy(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=gA(r);if(s!==void 0&&(n.reference!=="suffix"&&a.push("//"),a.push(s),r.path&&r.path[0]!=="/"&&a.push("/")),r.path!==void 0){let c=r.path;!n.absolutePath&&(!i||!i.absolutePath)&&(c=ya(c)),s===void 0&&c[0]==="/"&&c[1]==="/"&&(c="/%2F"+c.slice(2)),a.push(c)}return r.query!==void 0&&a.push("?",r.query),r.fragment!==void 0&&a.push("#",r.fragment),a.join("")}o(At,"serialize");var RA=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Qt(e,t){let r=Object.assign({},t),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},a=!1;r.reference==="suffix"&&(r.scheme?e=r.scheme+":"+e:e="//"+e);let i=e.match(RA);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(yA(n.host)===!1){let d=hA(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=xy(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&a===!1&&SA(n.host))try{n.host=URL.domainToASCII(n.host.toLowerCase())}catch(c){n.error=n.error||"Host's domain name can not be converted to ASCII: "+c}(!s||s&&!s.skipNormalize)&&(e.indexOf("%")!==-1&&(n.scheme!==void 0&&(n.scheme=unescape(n.scheme)),n.host!==void 0&&(n.host=unescape(n.host))),n.path&&(n.path=escape(unescape(n.path))),n.fragment&&(n.fragment=encodeURI(decodeURIComponent(n.fragment)))),s&&s.parse&&s.parse(n,r)}else n.error=n.error||"URI can not be parsed.";return n}o(Qt,"parse");var rl={SCHEMES:vA,normalize:_A,resolve:wA,resolveComponent:ky,equal:bA,serialize:At,parse:Qt};as.exports=rl;as.exports.default=rl;as.exports.fastUri=rl});var Ey=k(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});var Ay=Ty();Ay.code='require("ajv/dist/runtime/uri").default';nl.default=Ay});var Dy=k(Oe=>{"use strict";Object.defineProperty(Oe,"__esModule",{value:!0});Oe.CodeGen=Oe.Name=Oe.nil=Oe.stringify=Oe.str=Oe._=Oe.KeywordCxt=void 0;var CA=ha();Object.defineProperty(Oe,"KeywordCxt",{enumerable:!0,get:o(function(){return CA.KeywordCxt},"get")});var Wn=F();Object.defineProperty(Oe,"_",{enumerable:!0,get:o(function(){return Wn._},"get")});Object.defineProperty(Oe,"str",{enumerable:!0,get:o(function(){return Wn.str},"get")});Object.defineProperty(Oe,"stringify",{enumerable:!0,get:o(function(){return Wn.stringify},"get")});Object.defineProperty(Oe,"nil",{enumerable:!0,get:o(function(){return Wn.nil},"get")});Object.defineProperty(Oe,"Name",{enumerable:!0,get:o(function(){return Wn.Name},"get")});Object.defineProperty(Oe,"CodeGen",{enumerable:!0,get:o(function(){return Wn.CodeGen},"get")});var IA=Xi(),My=ga(),PA=Ud(),Sa=ts(),xA=F(),va=pa(),is=la(),al=te(),Uy=yy(),kA=Ey(),qy=o((e,t)=>new RegExp(e,t),"defaultRegExp");qy.code="new RegExp";var TA=["removeAdditional","useDefaults","coerceTypes"],AA=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),EA={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."},UA={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},Oy=200;function OA(e){var t,r,n,a,i,s,c,d,p,l,m,h,y,v,S,_,w,b,R,z,M,Me,at,yn,or;let Mt=e.strict,Er=(t=e.code)===null||t===void 0?void 0:t.optimize,po=Er===!0||Er===void 0?1:Er||0,mo=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:qy,fo=(a=e.uriResolver)!==null&&a!==void 0?a:kA.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:Mt)!==null&&s!==void 0?s:!0,strictNumbers:(d=(c=e.strictNumbers)!==null&&c!==void 0?c:Mt)!==null&&d!==void 0?d:!0,strictTypes:(l=(p=e.strictTypes)!==null&&p!==void 0?p:Mt)!==null&&l!==void 0?l:"log",strictTuples:(h=(m=e.strictTuples)!==null&&m!==void 0?m:Mt)!==null&&h!==void 0?h:"log",strictRequired:(v=(y=e.strictRequired)!==null&&y!==void 0?y:Mt)!==null&&v!==void 0?v:!1,code:e.code?{...e.code,optimize:po,regExp:mo}:{optimize:po,regExp:mo},loopRequired:(S=e.loopRequired)!==null&&S!==void 0?S:Oy,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:Oy,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!0,inlineRefs:(R=e.inlineRefs)!==null&&R!==void 0?R:!0,schemaId:(z=e.schemaId)!==null&&z!==void 0?z:"$id",addUsedSchema:(M=e.addUsedSchema)!==null&&M!==void 0?M:!0,validateSchema:(Me=e.validateSchema)!==null&&Me!==void 0?Me:!0,validateFormats:(at=e.validateFormats)!==null&&at!==void 0?at:!0,unicodeRegExp:(yn=e.unicodeRegExp)!==null&&yn!==void 0?yn:!0,int32range:(or=e.int32range)!==null&&or!==void 0?or:!0,uriResolver:fo}}o(OA,"requiredOptions");var _a=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,...OA(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new xA.ValueScope({scope:{},prefixes:AA,es5:r,lines:n}),this.logger=DA(t.logger);let a=t.validateFormats;t.validateFormats=!1,this.RULES=(0,PA.getRules)(),$y.call(this,EA,t,"NOT SUPPORTED"),$y.call(this,UA,t,"DEPRECATED","warn"),this._metaOpts=qA.call(this),t.formats&&zA.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&MA.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),$A.call(this),t.validateFormats=a}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,a=Uy;n==="id"&&(a={...Uy},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 My.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,va.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=zy.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,a=new Sa.SchemaEnv({schema:{},schemaId:n});if(r=Sa.resolveSchema.call(this,a,t),!r)return;this.refs[t]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(t){if(t instanceof RegExp)return this._removeAllSchemas(this.schemas,t),this._removeAllSchemas(this.refs,t),this;switch(typeof t){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=zy.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,va.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(HA.call(this,n,r),!r)return(0,al.eachItem)(n,i=>ol.call(this,i)),this;BA.call(this,r);let a={...r,type:(0,is.getJSONTypes)(r.type),schemaType:(0,is.getJSONTypes)(r.schemaType)};return(0,al.eachItem)(n,a.type.length===0?i=>ol.call(this,i,a):i=>a.type.forEach(s=>ol.call(this,i,a,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let a=n.rules.findIndex(i=>i.keyword===t);a>=0&&n.rules.splice(a,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(a=>`${n}${a.instancePath} ${a.message}`).reduce((a,i)=>a+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let a of r){let i=a.split("/").slice(1),s=t;for(let c of i)s=s[c];for(let c in n){let d=n[c];if(typeof d!="object")continue;let{$data:p}=d.definition,l=s[c];p&&l&&(s[c]=Ny(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,va.normalizeId)(s||n);let p=va.getSchemaRefs.call(this,t,n);return d=new Sa.SchemaEnv({schema:t,schemaId:c,meta:r,baseId:n,localRefs:p}),this._cache.set(d.schema,d),i&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=d),a&&this.validateSchema(t,!0),d}_checkUnique(t){if(this.schemas[t]||this.refs[t])throw new Error(`schema with key or id "${t}" already exists`)}_compileSchemaEnv(t){if(t.meta?this._compileMetaSchema(t):Sa.compileSchema.call(this,t),!t.validate)throw new Error("ajv implementation error");return t.validate}_compileMetaSchema(t){let r=this.opts;this.opts=this._metaOpts;try{Sa.compileSchema.call(this,t)}finally{this.opts=r}}};_a.ValidationError=IA.default;_a.MissingRefError=My.default;Oe.default=_a;function $y(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($y,"checkOptions");function zy(e){return e=(0,va.normalizeId)(e),this.schemas[e]||this.refs[e]}o(zy,"getSchEnv");function $A(){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($A,"addInitialSchemas");function zA(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}o(zA,"addInitialFormats");function MA(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(MA,"addInitialKeywords");function qA(){let e={...this.opts};for(let t of TA)delete e[t];return e}o(qA,"getMetaSchemaOptions");var NA={log(){},warn(){},error(){}};function DA(e){if(e===!1)return NA;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(DA,"getLogger");var jA=/^[a-z_$][a-z0-9_$:-]*$/i;function HA(e,t){let{RULES:r}=this;if((0,al.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!jA.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(HA,"checkKeyword");function ol(e,t,r){var n;let a=t?.post;if(r&&a)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=a?i.post:i.rules.find(({type:d})=>d===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;let c={keyword:e,definition:{...t,type:(0,is.getJSONTypes)(t.type),schemaType:(0,is.getJSONTypes)(t.schemaType)}};t.before?LA.call(this,s,c,t.before):s.rules.push(c),i.all[e]=c,(n=t.implements)===null||n===void 0||n.forEach(d=>this.addKeyword(d))}o(ol,"addRule");function LA(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(LA,"addBeforeRule");function BA(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Ny(t)),e.validateSchema=this.compile(t,!0))}o(BA,"keywordMetaschema");var GA={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ny(e){return{anyOf:[e,GA]}}o(Ny,"schemaOrData")});var jy=k(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});var VA={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};il.default=VA});var Gy=k(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.callRef=rn.getValidate=void 0;var FA=ga(),Hy=pt(),tt=F(),Yn=Wt(),Ly=ts(),ss=te(),ZA={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=Ly.resolveRef.call(d,p,a,r);if(l===void 0)throw new FA.default(n.opts.uriResolver,a,r);if(l instanceof Ly.SchemaEnv)return h(l);return y(l);function m(){if(i===p)return cs(e,s,i,i.$async);let v=t.scopeValue("root",{ref:p});return cs(e,(0,tt._)`${v}.validate`,p,p.$async)}function h(v){let S=By(e,v);cs(e,S,v,v.$async)}function y(v){let S=t.scopeValue("schema",c.code.source===!0?{ref:v,code:(0,tt.stringify)(v)}:{ref:v}),_=t.name("valid"),w=e.subschema({schema:v,dataTypes:[],schemaPath:tt.nil,topSchemaRef:S,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function By(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,tt._)`${r.scopeValue("wrapper",{ref:t})}.validate`}o(By,"getValidate");rn.getValidate=By;function cs(e,t,r,n){let{gen:a,it:i}=e,{allErrors:s,schemaEnv:c,opts:d}=i,p=d.passContext?Yn.default.this:tt.nil;n?l():m();function l(){if(!c.$async)throw new Error("async schema referenced by sync schema");let v=a.let("valid");a.try(()=>{a.code((0,tt._)`await ${(0,Hy.callValidateCode)(e,t,p)}`),y(t),s||a.assign(v,!0)},S=>{a.if((0,tt._)`!(${S} instanceof ${i.ValidationError})`,()=>a.throw(S)),h(S),s||a.assign(v,!1)}),e.ok(v)}o(l,"callAsyncRef");function m(){e.result((0,Hy.callValidateCode)(e,t,p),()=>y(t),()=>h(t))}o(m,"callSyncRef");function h(v){let S=(0,tt._)`${v}.errors`;a.assign(Yn.default.vErrors,(0,tt._)`${Yn.default.vErrors} === null ? ${S} : ${Yn.default.vErrors}.concat(${S})`),a.assign(Yn.default.errors,(0,tt._)`${Yn.default.vErrors}.length`)}o(h,"addErrorsFrom");function y(v){var S;if(!i.opts.unevaluated)return;let _=(S=r?.validate)===null||S===void 0?void 0:S.evaluated;if(i.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(i.props=ss.mergeEvaluated.props(a,_.props,i.props));else{let w=a.var("props",(0,tt._)`${v}.evaluated.props`);i.props=ss.mergeEvaluated.props(a,w,i.props,tt.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=ss.mergeEvaluated.items(a,_.items,i.items));else{let w=a.var("items",(0,tt._)`${v}.evaluated.items`);i.items=ss.mergeEvaluated.items(a,w,i.items,tt.Name)}}o(y,"addEvaluatedFrom")}o(cs,"callRef");rn.callRef=cs;rn.default=ZA});var Vy=k(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});var KA=jy(),JA=Gy(),WA=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",KA.default,JA.default];sl.default=WA});var Fy=k(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});var us=F(),Cr=us.operators,ds={maximum:{okStr:"<=",ok:Cr.LTE,fail:Cr.GT},minimum:{okStr:">=",ok:Cr.GTE,fail:Cr.LT},exclusiveMaximum:{okStr:"<",ok:Cr.LT,fail:Cr.GTE},exclusiveMinimum:{okStr:">",ok:Cr.GT,fail:Cr.LTE}},YA={message:o(({keyword:e,schemaCode:t})=>(0,us.str)`must be ${ds[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,us._)`{comparison: ${ds[e].okStr}, limit: ${t}}`,"params")},QA={keyword:Object.keys(ds),type:"number",schemaType:"number",$data:!0,error:YA,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,us._)`${r} ${ds[t].fail} ${n} || isNaN(${r})`)}};cl.default=QA});var Zy=k(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var wa=F(),XA={message:o(({schemaCode:e})=>(0,wa.str)`must be multiple of ${e}`,"message"),params:o(({schemaCode:e})=>(0,wa._)`{multipleOf: ${e}}`,"params")},e0={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:XA,code(e){let{gen:t,data:r,schemaCode:n,it:a}=e,i=a.opts.multipleOfPrecision,s=t.let("res"),c=i?(0,wa._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,wa._)`${s} !== parseInt(${s})`;e.fail$data((0,wa._)`(${n} === 0 || (${s} = ${r}/${n}, ${c}))`)}};ul.default=e0});var Jy=k(dl=>{"use strict";Object.defineProperty(dl,"__esModule",{value:!0});function Ky(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(Ky,"ucs2length");dl.default=Ky;Ky.code='require("ajv/dist/runtime/ucs2length").default'});var Wy=k(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});var nn=F(),t0=te(),r0=Jy(),n0={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,nn.str)`must NOT have ${r} than ${t} characters`},params:o(({schemaCode:e})=>(0,nn._)`{limit: ${e}}`,"params")},o0={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:n0,code(e){let{keyword:t,data:r,schemaCode:n,it:a}=e,i=t==="maxLength"?nn.operators.GT:nn.operators.LT,s=a.opts.unicode===!1?(0,nn._)`${r}.length`:(0,nn._)`${(0,t0.useFunc)(e.gen,r0.default)}(${r})`;e.fail$data((0,nn._)`${s} ${i} ${n}`)}};ll.default=o0});var Yy=k(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});var a0=pt(),ls=F(),i0={message:o(({schemaCode:e})=>(0,ls.str)`must match pattern "${e}"`,"message"),params:o(({schemaCode:e})=>(0,ls._)`{pattern: ${e}}`,"params")},s0={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:i0,code(e){let{data:t,$data:r,schema:n,schemaCode:a,it:i}=e,s=i.opts.unicodeRegExp?"u":"",c=r?(0,ls._)`(new RegExp(${a}, ${s}))`:(0,a0.usePattern)(e,n);e.fail$data((0,ls._)`!${c}.test(${t})`)}};pl.default=s0});var Qy=k(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});var ba=F(),c0={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,ba.str)`must NOT have ${r} than ${t} properties`},params:o(({schemaCode:e})=>(0,ba._)`{limit: ${e}}`,"params")},u0={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:c0,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxProperties"?ba.operators.GT:ba.operators.LT;e.fail$data((0,ba._)`Object.keys(${r}).length ${a} ${n}`)}};ml.default=u0});var Xy=k(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});var Ra=pt(),Ca=F(),d0=te(),l0={message:o(({params:{missingProperty:e}})=>(0,Ca.str)`must have required property '${e}'`,"message"),params:o(({params:{missingProperty:e}})=>(0,Ca._)`{missingProperty: ${e}}`,"params")},p0={keyword:"required",type:"object",schemaType:"array",$data:!0,error:l0,code(e){let{gen:t,schema:r,schemaCode:n,data:a,$data:i,it:s}=e,{opts:c}=s;if(!i&&r.length===0)return;let d=r.length>=c.loopRequired;if(s.allErrors?p():l(),c.strictRequired){let y=e.parentSchema.properties,{definedProperties:v}=e.it;for(let S of r)if(y?.[S]===void 0&&!v.has(S)){let _=s.schemaEnv.baseId+s.errSchemaPath,w=`required property "${S}" is not defined at "${_}" (strictRequired)`;(0,d0.checkStrictMode)(s,w,s.opts.strictRequired)}}function p(){if(d||i)e.block$data(Ca.nil,m);else for(let y of r)(0,Ra.checkReportMissingProp)(e,y)}o(p,"allErrorsMode");function l(){let y=t.let("missing");if(d||i){let v=t.let("valid",!0);e.block$data(v,()=>h(y,v)),e.ok(v)}else t.if((0,Ra.checkMissingProp)(e,r,y)),(0,Ra.reportMissingProp)(e,y),t.else()}o(l,"exitOnErrorMode");function m(){t.forOf("prop",n,y=>{e.setParams({missingProperty:y}),t.if((0,Ra.noPropertyInData)(t,a,y,c.ownProperties),()=>e.error())})}o(m,"loopAllRequired");function h(y,v){e.setParams({missingProperty:y}),t.forOf(y,n,()=>{t.assign(v,(0,Ra.propertyInData)(t,a,y,c.ownProperties)),t.if((0,Ca.not)(v),()=>{e.error(),t.break()})},Ca.nil)}o(h,"loopUntilMissing")}};fl.default=p0});var eS=k(hl=>{"use strict";Object.defineProperty(hl,"__esModule",{value:!0});var Ia=F(),m0={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,Ia.str)`must NOT have ${r} than ${t} items`},params:o(({schemaCode:e})=>(0,Ia._)`{limit: ${e}}`,"params")},f0={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:m0,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxItems"?Ia.operators.GT:Ia.operators.LT;e.fail$data((0,Ia._)`${r}.length ${a} ${n}`)}};hl.default=f0});var ps=k(gl=>{"use strict";Object.defineProperty(gl,"__esModule",{value:!0});var tS=jd();tS.code='require("ajv/dist/runtime/equal").default';gl.default=tS});var rS=k(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});var yl=la(),$e=F(),h0=te(),g0=ps(),y0={message:o(({params:{i:e,j:t}})=>(0,$e.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,"message"),params:o(({params:{i:e,j:t}})=>(0,$e._)`{i: ${e}, j: ${t}}`,"params")},S0={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:y0,code(e){let{gen:t,data:r,$data:n,schema:a,parentSchema:i,schemaCode:s,it:c}=e;if(!n&&!a)return;let d=t.let("valid"),p=i.items?(0,yl.getSchemaTypes)(i.items):[];e.block$data(d,l,(0,$e._)`${s} === false`),e.ok(d);function l(){let v=t.let("i",(0,$e._)`${r}.length`),S=t.let("j");e.setParams({i:v,j:S}),t.assign(d,!0),t.if((0,$e._)`${v} > 1`,()=>(m()?h:y)(v,S))}o(l,"validateUniqueItems");function m(){return p.length>0&&!p.some(v=>v==="object"||v==="array")}o(m,"canOptimize");function h(v,S){let _=t.name("item"),w=(0,yl.checkDataTypes)(p,_,c.opts.strictNumbers,yl.DataType.Wrong),b=t.const("indices",(0,$e._)`{}`);t.for((0,$e._)`;${v}--;`,()=>{t.let(_,(0,$e._)`${r}[${v}]`),t.if(w,(0,$e._)`continue`),p.length>1&&t.if((0,$e._)`typeof ${_} == "string"`,(0,$e._)`${_} += "_"`),t.if((0,$e._)`typeof ${b}[${_}] == "number"`,()=>{t.assign(S,(0,$e._)`${b}[${_}]`),e.error(),t.assign(d,!1).break()}).code((0,$e._)`${b}[${_}] = ${v}`)})}o(h,"loopN");function y(v,S){let _=(0,h0.useFunc)(t,g0.default),w=t.name("outer");t.label(w).for((0,$e._)`;${v}--;`,()=>t.for((0,$e._)`${S} = ${v}; ${S}--;`,()=>t.if((0,$e._)`${_}(${r}[${v}], ${r}[${S}])`,()=>{e.error(),t.assign(d,!1).break(w)})))}o(y,"loopN2")}};Sl.default=S0});var nS=k(_l=>{"use strict";Object.defineProperty(_l,"__esModule",{value:!0});var vl=F(),v0=te(),_0=ps(),w0={message:"must be equal to constant",params:o(({schemaCode:e})=>(0,vl._)`{allowedValue: ${e}}`,"params")},b0={keyword:"const",$data:!0,error:w0,code(e){let{gen:t,data:r,$data:n,schemaCode:a,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,vl._)`!${(0,v0.useFunc)(t,_0.default)}(${r}, ${a})`):e.fail((0,vl._)`${i} !== ${r}`)}};_l.default=b0});var oS=k(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});var Pa=F(),R0=te(),C0=ps(),I0={message:"must be equal to one of the allowed values",params:o(({schemaCode:e})=>(0,Pa._)`{allowedValues: ${e}}`,"params")},P0={keyword:"enum",schemaType:"array",$data:!0,error:I0,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,R0.useFunc)(t,C0.default)),"getEql"),l;if(c||n)l=t.let("valid"),e.block$data(l,m);else{if(!Array.isArray(a))throw new Error("ajv implementation error");let y=t.const("vSchema",i);l=(0,Pa.or)(...a.map((v,S)=>h(y,S)))}e.pass(l);function m(){t.assign(l,!1),t.forOf("v",i,y=>t.if((0,Pa._)`${p()}(${r}, ${y})`,()=>t.assign(l,!0).break()))}o(m,"loopEnum");function h(y,v){let S=a[v];return typeof S=="object"&&S!==null?(0,Pa._)`${p()}(${r}, ${y}[${v}])`:(0,Pa._)`${r} === ${S}`}o(h,"equalCode")}};wl.default=P0});var aS=k(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});var x0=Fy(),k0=Zy(),T0=Wy(),A0=Yy(),E0=Qy(),U0=Xy(),O0=eS(),$0=rS(),z0=nS(),M0=oS(),q0=[x0.default,k0.default,T0.default,A0.default,E0.default,U0.default,O0.default,$0.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},z0.default,M0.default];bl.default=q0});var Cl=k(xa=>{"use strict";Object.defineProperty(xa,"__esModule",{value:!0});xa.validateAdditionalItems=void 0;var on=F(),Rl=te(),N0={message:o(({params:{len:e}})=>(0,on.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,on._)`{limit: ${e}}`,"params")},D0={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:N0,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Rl.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}iS(e,n)}};function iS(e,t){let{gen:r,schema:n,data:a,keyword:i,it:s}=e;s.items=!0;let c=r.const("len",(0,on._)`${a}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,on._)`${c} <= ${t.length}`);else if(typeof n=="object"&&!(0,Rl.alwaysValidSchema)(s,n)){let p=r.var("valid",(0,on._)`${c} <= ${t.length}`);r.if((0,on.not)(p),()=>d(p)),e.ok(p)}function d(p){r.forRange("i",t.length,c,l=>{e.subschema({keyword:i,dataProp:l,dataPropType:Rl.Type.Num},p),s.allErrors||r.if((0,on.not)(p),()=>r.break())})}o(d,"validateItems")}o(iS,"validateAdditionalItems");xa.validateAdditionalItems=iS;xa.default=D0});var Il=k(ka=>{"use strict";Object.defineProperty(ka,"__esModule",{value:!0});ka.validateTuple=void 0;var sS=F(),ms=te(),j0=pt(),H0={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return cS(e,"additionalItems",t);r.items=!0,!(0,ms.alwaysValidSchema)(r,t)&&e.ok((0,j0.validateArray)(e))}};function cS(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=ms.mergeEvaluated.items(n,r.length,c.items));let d=n.name("valid"),p=n.const("len",(0,sS._)`${i}.length`);r.forEach((m,h)=>{(0,ms.alwaysValidSchema)(c,m)||(n.if((0,sS._)`${p} > ${h}`,()=>e.subschema({keyword:s,schemaProp:h,dataProp:h},d)),e.ok(d))});function l(m){let{opts:h,errSchemaPath:y}=c,v=r.length,S=v===m.minItems&&(v===m.maxItems||m[t]===!1);if(h.strictTuples&&!S){let _=`"${s}" is ${v}-tuple, but minItems or maxItems/${t} are not specified or different at path "${y}"`;(0,ms.checkStrictMode)(c,_,h.strictTuples)}}o(l,"checkStrictTuple")}o(cS,"validateTuple");ka.validateTuple=cS;ka.default=H0});var uS=k(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});var L0=Il(),B0={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:o(e=>(0,L0.validateTuple)(e,"items"),"code")};Pl.default=B0});var lS=k(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});var dS=F(),G0=te(),V0=pt(),F0=Cl(),Z0={message:o(({params:{len:e}})=>(0,dS.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,dS._)`{limit: ${e}}`,"params")},K0={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Z0,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:a}=r;n.items=!0,!(0,G0.alwaysValidSchema)(n,t)&&(a?(0,F0.validateAdditionalItems)(e,a):e.ok((0,V0.validateArray)(e)))}};xl.default=K0});var pS=k(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});var ft=F(),fs=te(),J0={message:o(({params:{min:e,max:t}})=>t===void 0?(0,ft.str)`must contain at least ${e} valid item(s)`:(0,ft.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,ft._)`{minContains: ${e}}`:(0,ft._)`{minContains: ${e}, maxContains: ${t}}`,"params")},W0={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:J0,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,ft._)`${a}.length`);if(e.setParams({min:s,max:c}),c===void 0&&s===0){(0,fs.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&s>c){(0,fs.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,fs.alwaysValidSchema)(i,r)){let S=(0,ft._)`${l} >= ${s}`;c!==void 0&&(S=(0,ft._)`${S} && ${l} <= ${c}`),e.pass(S);return}i.items=!0;let m=t.name("valid");c===void 0&&s===1?y(m,()=>t.if(m,()=>t.break())):s===0?(t.let(m,!0),c!==void 0&&t.if((0,ft._)`${a}.length > 0`,h)):(t.let(m,!1),h()),e.result(m,()=>e.reset());function h(){let S=t.name("_valid"),_=t.let("count",0);y(S,()=>t.if(S,()=>v(_)))}o(h,"validateItemsWithCount");function y(S,_){t.forRange("i",0,l,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:fs.Type.Num,compositeRule:!0},S),_()})}o(y,"validateItems");function v(S){t.code((0,ft._)`${S}++`),c===void 0?t.if((0,ft._)`${S} >= ${s}`,()=>t.assign(m,!0).break()):(t.if((0,ft._)`${S} > ${c}`,()=>t.assign(m,!1).break()),s===1?t.assign(m,!0):t.if((0,ft._)`${S} >= ${s}`,()=>t.assign(m,!0)))}o(v,"checkLimits")}};kl.default=W0});var hS=k(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.validateSchemaDeps=Et.validatePropertyDeps=Et.error=void 0;var Tl=F(),Y0=te(),Ta=pt();Et.error={message:o(({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Tl.str)`must have ${n} ${r} when property ${e} is present`},"message"),params:o(({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Tl._)`{property: ${e},
|
|
29
|
+
|| ${s} === "boolean" || ${a} === null`).assign(c,(0,G._)`[${a}]`)}}o(d,"coerceSpecificType")}o(Nk,"coerceData");function jk({gen:e,parentData:t,parentDataProperty:r},n){e.if((0,G._)`${t} !== undefined`,()=>e.assign((0,G._)`${t}[${r}]`,n))}o(jk,"assignParentData");function $d(e,t,r,n=Jn.Correct){let a=n===Jn.Correct?G.operators.EQ:G.operators.NEQ,i;switch(e){case"null":return(0,G._)`${t} ${a} null`;case"array":i=(0,G._)`Array.isArray(${t})`;break;case"object":i=(0,G._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case"integer":i=s((0,G._)`!(${t} % 1) && !isNaN(${t})`);break;case"number":i=s();break;default:return(0,G._)`typeof ${t} ${a} ${e}`}return n===Jn.Correct?i:(0,G.not)(i);function s(c=G.nil){return(0,G.and)((0,G._)`typeof ${t} == "number"`,c,r?(0,G._)`isFinite(${t})`:G.nil)}}o($d,"checkDataType");Be.checkDataType=$d;function Md(e,t,r,n){if(e.length===1)return $d(e[0],t,r,n);let a,i=(0,Zg.toHash)(e);if(i.array&&i.object){let s=(0,G._)`typeof ${t} != "object"`;a=i.null?s:(0,G._)`!${t} || ${s}`,delete i.null,delete i.array,delete i.object}else a=G.nil;i.number&&delete i.integer;for(let s in i)a=(0,G.and)(a,$d(s,t,r,n));return a}o(Md,"checkDataTypes");Be.checkDataTypes=Md;var Dk={message:o(({schema:e})=>`must be ${e}`,"message"),params:o(({schema:e,schemaValue:t})=>typeof e=="string"?(0,G._)`{type: ${e}}`:(0,G._)`{type: ${t}}`,"params")};function zd(e){let t=Hk(e);(0,$k.reportError)(t,Dk)}o(zd,"reportTypeError");Be.reportTypeError=zd;function Hk(e){let{gen:t,data:r,schema:n}=e,a=(0,Zg.schemaRefOrVal)(e,n,"type");return{gen:t,keyword:"type",data:r,schema:n.type,schemaCode:a,schemaValue:a,parentSchema:n,params:{},it:e}}o(Hk,"getTypeErrorContext")});var Yg=k(Qi=>{"use strict";Object.defineProperty(Qi,"__esModule",{value:!0});Qi.assignDefaults=void 0;var Wn=F(),Lk=te();function Bk(e,t){let{properties:r,items:n}=e.schema;if(t==="object"&&r)for(let a in r)Wg(e,a,r[a].default);else t==="array"&&Array.isArray(n)&&n.forEach((a,i)=>Wg(e,i,a.default))}o(Bk,"assignDefaults");Qi.assignDefaults=Bk;function Wg(e,t,r){let{gen:n,compositeRule:a,data:i,opts:s}=e;if(r===void 0)return;let c=(0,Wn._)`${i}${(0,Wn.getProperty)(t)}`;if(a){(0,Lk.checkStrictMode)(e,`default is ignored for: ${c}`);return}let d=(0,Wn._)`${c} === undefined`;s.useDefaults==="empty"&&(d=(0,Wn._)`${d} || ${c} === null || ${c} === ""`),n.if(d,(0,Wn._)`${c} = ${(0,Wn.stringify)(r)}`)}o(Wg,"assignDefault")});var gt=k(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.validateUnion=ne.validateArray=ne.usePattern=ne.callValidateCode=ne.schemaProperties=ne.allSchemaProperties=ne.noPropertyInData=ne.propertyInData=ne.isOwnProperty=ne.hasPropFunc=ne.reportMissingProp=ne.checkMissingProp=ne.checkReportMissingProp=void 0;var pe=F(),qd=te(),Pr=Xt(),Gk=te();function Vk(e,t){let{gen:r,data:n,it:a}=e;r.if(jd(r,n,t,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,pe._)`${t}`},!0),e.error()})}o(Vk,"checkReportMissingProp");ne.checkReportMissingProp=Vk;function Fk({gen:e,data:t,it:{opts:r}},n,a){return(0,pe.or)(...n.map(i=>(0,pe.and)(jd(e,t,i,r.ownProperties),(0,pe._)`${a} = ${i}`)))}o(Fk,"checkMissingProp");ne.checkMissingProp=Fk;function Zk(e,t){e.setParams({missingProperty:t},!0),e.error()}o(Zk,"reportMissingProp");ne.reportMissingProp=Zk;function Qg(e){return e.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,pe._)`Object.prototype.hasOwnProperty`})}o(Qg,"hasPropFunc");ne.hasPropFunc=Qg;function Nd(e,t,r){return(0,pe._)`${Qg(e)}.call(${t}, ${r})`}o(Nd,"isOwnProperty");ne.isOwnProperty=Nd;function Kk(e,t,r,n){let a=(0,pe._)`${t}${(0,pe.getProperty)(r)} !== undefined`;return n?(0,pe._)`${a} && ${Nd(e,t,r)}`:a}o(Kk,"propertyInData");ne.propertyInData=Kk;function jd(e,t,r,n){let a=(0,pe._)`${t}${(0,pe.getProperty)(r)} === undefined`;return n?(0,pe.or)(a,(0,pe.not)(Nd(e,t,r))):a}o(jd,"noPropertyInData");ne.noPropertyInData=jd;function Xg(e){return e?Object.keys(e).filter(t=>t!=="__proto__"):[]}o(Xg,"allSchemaProperties");ne.allSchemaProperties=Xg;function Jk(e,t){return Xg(t).filter(r=>!(0,qd.alwaysValidSchema)(e,t[r]))}o(Jk,"schemaProperties");ne.schemaProperties=Jk;function Wk({schemaCode:e,data:t,it:{gen:r,topSchemaRef:n,schemaPath:a,errorPath:i},it:s},c,d,p){let l=p?(0,pe._)`${e}, ${t}, ${n}${a}`:t,m=[[Pr.default.instancePath,(0,pe.strConcat)(Pr.default.instancePath,i)],[Pr.default.parentData,s.parentData],[Pr.default.parentDataProperty,s.parentDataProperty],[Pr.default.rootData,Pr.default.rootData]];s.opts.dynamicRef&&m.push([Pr.default.dynamicAnchors,Pr.default.dynamicAnchors]);let h=(0,pe._)`${l}, ${r.object(...m)}`;return d!==pe.nil?(0,pe._)`${c}.call(${d}, ${h})`:(0,pe._)`${c}(${h})`}o(Wk,"callValidateCode");ne.callValidateCode=Wk;var Yk=(0,pe._)`new RegExp`;function Qk({gen:e,it:{opts:t}},r){let n=t.unicodeRegExp?"u":"",{regExp:a}=t.code,i=a(r,n);return e.scopeValue("pattern",{key:i.toString(),ref:i,code:(0,pe._)`${a.code==="new RegExp"?Yk:(0,Gk.useFunc)(e,a)}(${r}, ${n})`})}o(Qk,"usePattern");ne.usePattern=Qk;function Xk(e){let{gen:t,data:r,keyword:n,it:a}=e,i=t.name("valid");if(a.allErrors){let c=t.let("valid",!0);return s(()=>t.assign(c,!1)),c}return t.var(i,!0),s(()=>t.break()),i;function s(c){let d=t.const("len",(0,pe._)`${r}.length`);t.forRange("i",0,d,p=>{e.subschema({keyword:n,dataProp:p,dataPropType:qd.Type.Num},i),t.if((0,pe.not)(i),c)})}o(s,"validateItems")}o(Xk,"validateArray");ne.validateArray=Xk;function eT(e){let{gen:t,schema:r,keyword:n,it:a}=e;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(d=>(0,qd.alwaysValidSchema)(a,d))&&!a.opts.unevaluated)return;let s=t.let("valid",!1),c=t.name("_valid");t.block(()=>r.forEach((d,p)=>{let l=e.subschema({keyword:n,schemaProp:p,compositeRule:!0},c);t.assign(s,(0,pe._)`${s} || ${c}`),e.mergeValidEvaluated(l,c)||t.if((0,pe.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}o(eT,"validateUnion");ne.validateUnion=eT});var ry=k(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.validateKeywordUsage=Ut.validSchemaType=Ut.funcKeywordCode=Ut.macroKeywordCode=void 0;var Fe=F(),on=Xt(),tT=gt(),rT=pa();function nT(e,t){let{gen:r,keyword:n,schema:a,parentSchema:i,it:s}=e,c=t.macro.call(s.self,a,i,s),d=ty(r,n,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let p=r.name("valid");e.subschema({schema:c,schemaPath:Fe.nil,errSchemaPath:`${s.errSchemaPath}/${n}`,topSchemaRef:d,compositeRule:!0},p),e.pass(p,()=>e.error(!0))}o(nT,"macroKeywordCode");Ut.macroKeywordCode=nT;function oT(e,t){var r;let{gen:n,keyword:a,schema:i,parentSchema:s,$data:c,it:d}=e;iT(d,t);let p=!c&&t.compile?t.compile.call(d.self,i,s,d):t.validate,l=ty(n,a,p),m=n.let("valid");e.block$data(m,h),e.ok((r=t.valid)!==null&&r!==void 0?r:m);function h(){if(t.errors===!1)S(),t.modifying&&ey(e),_(()=>e.error());else{let w=t.async?y():v();t.modifying&&ey(e),_(()=>aT(e,w))}}o(h,"validateKeyword");function y(){let w=n.let("ruleErrs",null);return n.try(()=>S((0,Fe._)`await `),b=>n.assign(m,!1).if((0,Fe._)`${b} instanceof ${d.ValidationError}`,()=>n.assign(w,(0,Fe._)`${b}.errors`),()=>n.throw(b))),w}o(y,"validateAsync");function v(){let w=(0,Fe._)`${l}.errors`;return n.assign(w,null),S(Fe.nil),w}o(v,"validateSync");function S(w=t.async?(0,Fe._)`await `:Fe.nil){let b=d.opts.passContext?on.default.this:on.default.self,R=!("compile"in t&&!c||t.schema===!1);n.assign(m,(0,Fe._)`${w}${(0,tT.callValidateCode)(e,l,b,R)}`,t.modifying)}o(S,"assignValid");function _(w){var b;n.if((0,Fe.not)((b=t.valid)!==null&&b!==void 0?b:m),w)}o(_,"reportErrs")}o(oT,"funcKeywordCode");Ut.funcKeywordCode=oT;function ey(e){let{gen:t,data:r,it:n}=e;t.if(n.parentData,()=>t.assign(r,(0,Fe._)`${n.parentData}[${n.parentDataProperty}]`))}o(ey,"modifyData");function aT(e,t){let{gen:r}=e;r.if((0,Fe._)`Array.isArray(${t})`,()=>{r.assign(on.default.vErrors,(0,Fe._)`${on.default.vErrors} === null ? ${t} : ${on.default.vErrors}.concat(${t})`).assign(on.default.errors,(0,Fe._)`${on.default.vErrors}.length`),(0,rT.extendErrors)(e)},()=>e.error())}o(aT,"addErrs");function iT({schemaEnv:e},t){if(t.async&&!e.$async)throw new Error("async keyword in sync schema")}o(iT,"checkAsyncKeyword");function ty(e,t,r){if(r===void 0)throw new Error(`keyword "${t}" failed to compile`);return e.scopeValue("keyword",typeof r=="function"?{ref:r}:{ref:r,code:(0,Fe.stringify)(r)})}o(ty,"useKeyword");function sT(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(sT,"validSchemaType");Ut.validSchemaType=sT;function cT({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(cT,"validateKeywordUsage");Ut.validateKeywordUsage=cT});var oy=k(xr=>{"use strict";Object.defineProperty(xr,"__esModule",{value:!0});xr.extendSubschemaMode=xr.extendSubschemaData=xr.getSubschema=void 0;var Ot=F(),ny=te();function uT(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,Ot._)`${e.schemaPath}${(0,Ot.getProperty)(t)}`,errSchemaPath:`${e.errSchemaPath}/${t}`}:{schema:c[r],schemaPath:(0,Ot._)`${e.schemaPath}${(0,Ot.getProperty)(t)}${(0,Ot.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${t}/${(0,ny.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(uT,"getSubschema");xr.getSubschema=uT;function dT(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,Ot._)`${t.data}${(0,Ot.getProperty)(r)}`,!0);d(h),e.errorPath=(0,Ot.str)`${p}${(0,ny.getErrorPath)(r,n,m.jsPropertySyntax)}`,e.parentDataProperty=(0,Ot._)`${r}`,e.dataPathArr=[...l,e.parentDataProperty]}if(a!==void 0){let p=a instanceof Ot.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(dT,"extendSubschemaData");xr.extendSubschemaData=dT;function lT(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(lT,"extendSubschemaMode");xr.extendSubschemaMode=lT});var Dd=k((_9,ay)=>{"use strict";ay.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 sy=k((b9,iy)=>{"use strict";var kr=iy.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(){};Xi(t,n,a,e,"",e)};kr.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};kr.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};kr.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};kr.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 Xi(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 kr.arrayKeywords)for(var h=0;h<m.length;h++)Xi(e,t,r,m[h],a+"/"+l+"/"+h,i,a,l,n,h)}else if(l in kr.propsKeywords){if(m&&typeof m=="object")for(var y in m)Xi(e,t,r,m[y],a+"/"+l+"/"+pT(y),i,a,l,n,y)}else(l in kr.keywords||e.allKeys&&!(l in kr.skipKeywords))&&Xi(e,t,r,m,a+"/"+l,i,a,l,n)}r(n,a,i,s,c,d,p)}}o(Xi,"_traverse");function pT(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(pT,"escapeJsonPtr")});var fa=k(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.getSchemaRefs=tt.resolveUrl=tt.normalizeId=tt._getFullPath=tt.getFullPath=tt.inlineRef=void 0;var mT=te(),fT=Dd(),hT=sy(),gT=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function yT(e,t=!0){return typeof e=="boolean"?!0:t===!0?!Hd(e):t?cy(e)<=t:!1}o(yT,"inlineRef");tt.inlineRef=yT;var ST=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Hd(e){for(let t in e){if(ST.has(t))return!0;let r=e[t];if(Array.isArray(r)&&r.some(Hd)||typeof r=="object"&&Hd(r))return!0}return!1}o(Hd,"hasRef");function cy(e){let t=0;for(let r in e){if(r==="$ref")return 1/0;if(t++,!gT.has(r)&&(typeof e[r]=="object"&&(0,mT.eachItem)(e[r],n=>t+=cy(n)),t===1/0))return 1/0}return t}o(cy,"countKeys");function uy(e,t="",r){r!==!1&&(t=Yn(t));let n=e.parse(t);return dy(e,n)}o(uy,"getFullPath");tt.getFullPath=uy;function dy(e,t){return e.serialize(t).split("#")[0]+"#"}o(dy,"_getFullPath");tt._getFullPath=dy;var vT=/#\/?$/;function Yn(e){return e?e.replace(vT,""):""}o(Yn,"normalizeId");tt.normalizeId=Yn;function _T(e,t,r){return r=Yn(r),e.resolve(t,r)}o(_T,"resolveUrl");tt.resolveUrl=_T;var wT=/^[a-z_][-a-z0-9._]*$/i;function bT(e,t){if(typeof e=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,a=Yn(e[r]||t),i={"":a},s=uy(n,a,!1),c={},d=new Set;return hT(e,{allKeys:!0},(m,h,y,v)=>{if(v===void 0)return;let S=s+h,_=i[v];typeof m[r]=="string"&&(_=w.call(this,m[r])),b.call(this,m.$anchor),b.call(this,m.$dynamicAnchor),i[h]=_;function w(R){let z=this.opts.uriResolver.resolve;if(R=Yn(_?z(_,R):R),d.has(R))throw l(R);d.add(R);let q=this.refs[R];return typeof q=="string"&&(q=this.refs[q]),typeof q=="object"?p(m,q.schema,R):R!==Yn(S)&&(R[0]==="#"?(p(m,c[R],R),c[R]=m):this.refs[R]=S),R}o(w,"addRef");function b(R){if(typeof R=="string"){if(!wT.test(R))throw new Error(`invalid anchor "${R}"`);w.call(this,`#${R}`)}}o(b,"addAnchor")}),c;function p(m,h,y){if(h!==void 0&&!fT(m,h))throw l(y)}o(p,"checkAmbiguosRef");function l(m){return new Error(`reference "${m}" resolves to more than one schema`)}o(l,"ambiguos")}o(bT,"getSchemaRefs");tt.getSchemaRefs=bT});var ya=k(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.getData=Tr.KeywordCxt=Tr.validateFunctionCode=void 0;var hy=Gg(),ly=ma(),Bd=Od(),es=ma(),RT=Yg(),ga=ry(),Ld=oy(),O=F(),H=Xt(),CT=fa(),er=te(),ha=pa();function IT(e){if(Sy(e)&&(vy(e),yy(e))){kT(e);return}gy(e,()=>(0,hy.topBoolOrEmptySchema)(e))}o(IT,"validateFunctionCode");Tr.validateFunctionCode=IT;function gy({gen:e,validateName:t,schema:r,schemaEnv:n,opts:a},i){a.code.es5?e.func(t,(0,O._)`${H.default.data}, ${H.default.valCxt}`,n.$async,()=>{e.code((0,O._)`"use strict"; ${py(r,a)}`),xT(e,a),e.code(i)}):e.func(t,(0,O._)`${H.default.data}, ${PT(a)}`,n.$async,()=>e.code(py(r,a)).code(i))}o(gy,"validateFunction");function PT(e){return(0,O._)`{${H.default.instancePath}="", ${H.default.parentData}, ${H.default.parentDataProperty}, ${H.default.rootData}=${H.default.data}${e.dynamicRef?(0,O._)`, ${H.default.dynamicAnchors}={}`:O.nil}}={}`}o(PT,"destructureValCxt");function xT(e,t){e.if(H.default.valCxt,()=>{e.var(H.default.instancePath,(0,O._)`${H.default.valCxt}.${H.default.instancePath}`),e.var(H.default.parentData,(0,O._)`${H.default.valCxt}.${H.default.parentData}`),e.var(H.default.parentDataProperty,(0,O._)`${H.default.valCxt}.${H.default.parentDataProperty}`),e.var(H.default.rootData,(0,O._)`${H.default.valCxt}.${H.default.rootData}`),t.dynamicRef&&e.var(H.default.dynamicAnchors,(0,O._)`${H.default.valCxt}.${H.default.dynamicAnchors}`)},()=>{e.var(H.default.instancePath,(0,O._)`""`),e.var(H.default.parentData,(0,O._)`undefined`),e.var(H.default.parentDataProperty,(0,O._)`undefined`),e.var(H.default.rootData,H.default.data),t.dynamicRef&&e.var(H.default.dynamicAnchors,(0,O._)`{}`)})}o(xT,"destructureValCxtES5");function kT(e){let{schema:t,opts:r,gen:n}=e;gy(e,()=>{r.$comment&&t.$comment&&wy(e),OT(e),n.let(H.default.vErrors,null),n.let(H.default.errors,0),r.unevaluated&&TT(e),_y(e),zT(e)})}o(kT,"topSchemaObjCode");function TT(e){let{gen:t,validateName:r}=e;e.evaluated=t.const("evaluated",(0,O._)`${r}.evaluated`),t.if((0,O._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,O._)`${e.evaluated}.props`,(0,O._)`undefined`)),t.if((0,O._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,O._)`${e.evaluated}.items`,(0,O._)`undefined`))}o(TT,"resetEvaluated");function py(e,t){let r=typeof e=="object"&&e[t.schemaId];return r&&(t.code.source||t.code.process)?(0,O._)`/*# sourceURL=${r} */`:O.nil}o(py,"funcSourceUrl");function AT(e,t){if(Sy(e)&&(vy(e),yy(e))){ET(e,t);return}(0,hy.boolOrEmptySchema)(e,t)}o(AT,"subschemaCode");function yy({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(yy,"schemaCxtHasRules");function Sy(e){return typeof e.schema!="boolean"}o(Sy,"isSchemaObj");function ET(e,t){let{schema:r,gen:n,opts:a}=e;a.$comment&&r.$comment&&wy(e),$T(e),MT(e);let i=n.const("_errs",H.default.errors);_y(e,i),n.var(t,(0,O._)`${i} === ${H.default.errors}`)}o(ET,"subSchemaObjCode");function vy(e){(0,er.checkUnknownRules)(e),UT(e)}o(vy,"checkKeywords");function _y(e,t){if(e.opts.jtd)return my(e,[],!1,t);let r=(0,ly.getSchemaTypes)(e.schema),n=(0,ly.coerceAndCheckDataType)(e,r);my(e,r,!n,t)}o(_y,"typeAndKeywords");function UT(e){let{schema:t,errSchemaPath:r,opts:n,self:a}=e;t.$ref&&n.ignoreKeywordsWithRef&&(0,er.schemaHasRulesButRef)(t,a.RULES)&&a.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}o(UT,"checkRefsAndKeywords");function OT(e){let{schema:t,opts:r}=e;t.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,er.checkStrictMode)(e,"default is ignored in the schema root")}o(OT,"checkNoDefault");function $T(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,CT.resolveUrl)(e.opts.uriResolver,e.baseId,t))}o($T,"updateContext");function MT(e){if(e.schema.$async&&!e.schemaEnv.$async)throw new Error("async schema in sync schema")}o(MT,"checkAsyncSchema");function wy({gen:e,schemaEnv:t,schema:r,errSchemaPath:n,opts:a}){let i=r.$comment;if(a.$comment===!0)e.code((0,O._)`${H.default.self}.logger.log(${i})`);else if(typeof a.$comment=="function"){let s=(0,O.str)`${n}/$comment`,c=e.scopeValue("root",{ref:t.root});e.code((0,O._)`${H.default.self}.opts.$comment(${i}, ${s}, ${c}.schema)`)}}o(wy,"commentKeyword");function zT(e){let{gen:t,schemaEnv:r,validateName:n,ValidationError:a,opts:i}=e;r.$async?t.if((0,O._)`${H.default.errors} === 0`,()=>t.return(H.default.data),()=>t.throw((0,O._)`new ${a}(${H.default.vErrors})`)):(t.assign((0,O._)`${n}.errors`,H.default.vErrors),i.unevaluated&&qT(e),t.return((0,O._)`${H.default.errors} === 0`))}o(zT,"returnResults");function qT({gen:e,evaluated:t,props:r,items:n}){r instanceof O.Name&&e.assign((0,O._)`${t}.props`,r),n instanceof O.Name&&e.assign((0,O._)`${t}.items`,n)}o(qT,"assignEvaluated");function my(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,er.schemaHasRulesButRef)(i,l))){a.block(()=>Ry(e,"$ref",l.all.$ref.definition));return}d.jtd||NT(e,t),a.block(()=>{for(let h of l.rules)m(h);m(l.post)});function m(h){(0,Bd.shouldUseGroup)(i,h)&&(h.type?(a.if((0,es.checkDataType)(h.type,s,d.strictNumbers)),fy(e,h),t.length===1&&t[0]===h.type&&r&&(a.else(),(0,es.reportTypeError)(e)),a.endIf()):fy(e,h),c||a.if((0,O._)`${H.default.errors} === ${n||0}`))}o(m,"groupKeywords")}o(my,"schemaKeywords");function fy(e,t){let{gen:r,schema:n,opts:{useDefaults:a}}=e;a&&(0,RT.assignDefaults)(e,t.type),r.block(()=>{for(let i of t.rules)(0,Bd.shouldUseRule)(n,i)&&Ry(e,i.keyword,i.definition,t.type)})}o(fy,"iterateKeywords");function NT(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(jT(e,t),e.opts.allowUnionTypes||DT(e,t),HT(e,e.dataTypes))}o(NT,"checkStrictTypes");function jT(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(r=>{by(e.dataTypes,r)||Gd(e,`type "${r}" not allowed by context "${e.dataTypes.join(",")}"`)}),BT(e,t)}}o(jT,"checkContextTypes");function DT(e,t){t.length>1&&!(t.length===2&&t.includes("null"))&&Gd(e,"use allowUnionTypes to allow union type keyword")}o(DT,"checkMultipleTypes");function HT(e,t){let r=e.self.RULES.all;for(let n in r){let a=r[n];if(typeof a=="object"&&(0,Bd.shouldUseRule)(e.schema,a)){let{type:i}=a.definition;i.length&&!i.some(s=>LT(t,s))&&Gd(e,`missing type "${i.join(",")}" for keyword "${n}"`)}}}o(HT,"checkKeywordTypes");function LT(e,t){return e.includes(t)||t==="number"&&e.includes("integer")}o(LT,"hasApplicableType");function by(e,t){return e.includes(t)||t==="integer"&&e.includes("number")}o(by,"includesType");function BT(e,t){let r=[];for(let n of e.dataTypes)by(t,n)?r.push(n):t.includes("integer")&&n==="number"&&r.push("integer");e.dataTypes=r}o(BT,"narrowSchemaTypes");function Gd(e,t){let r=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${r}" (strictTypes)`,(0,er.checkStrictMode)(e,t,e.opts.strictTypes)}o(Gd,"strictTypesError");var ts=class{static{o(this,"KeywordCxt")}constructor(t,r,n){if((0,ga.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,er.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",Cy(this.$data,t));else if(this.schemaCode=this.schemaValue,!(0,ga.validSchemaType)(this.schema,r.schemaType,r.allowUndefined))throw new Error(`${n} value must be ${JSON.stringify(r.schemaType)}`);("code"in r?r.trackErrors:r.errors!==!1)&&(this.errsCount=t.gen.const("_errs",H.default.errors))}result(t,r,n){this.failResult((0,O.not)(t),r,n)}failResult(t,r,n){this.gen.if(t),n?n():this.error(),r?(this.gen.else(),r(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(t,r){this.failResult((0,O.not)(t),void 0,r)}fail(t){if(t===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(t),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(t){if(!this.$data)return this.fail(t);let{schemaCode:r}=this;this.fail((0,O._)`${r} !== undefined && (${(0,O.or)(this.invalid$data(),t)})`)}error(t,r,n){if(r){this.setParams(r),this._error(t,n),this.setParams({});return}this._error(t,n)}_error(t,r){(t?ha.reportExtraError:ha.reportError)(this,this.def.error,r)}$dataError(){(0,ha.reportError)(this,this.def.$dataError||ha.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ha.resetErrorsCount)(this.gen,this.errsCount)}ok(t){this.allErrors||this.gen.if(t)}setParams(t,r){r?Object.assign(this.params,t):this.params=t}block$data(t,r,n=O.nil){this.gen.block(()=>{this.check$data(t,n),r()})}check$data(t=O.nil,r=O.nil){if(!this.$data)return;let{gen:n,schemaCode:a,schemaType:i,def:s}=this;n.if((0,O.or)((0,O._)`${a} === undefined`,r)),t!==O.nil&&n.assign(t,!0),(i.length||s.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),t!==O.nil&&n.assign(t,!1)),n.else()}invalid$data(){let{gen:t,schemaCode:r,schemaType:n,def:a,it:i}=this;return(0,O.or)(s(),c());function s(){if(n.length){if(!(r instanceof O.Name))throw new Error("ajv implementation error");let d=Array.isArray(n)?n:[n];return(0,O._)`${(0,es.checkDataTypes)(d,r,i.opts.strictNumbers,es.DataType.Wrong)}`}return O.nil}function c(){if(a.validateSchema){let d=t.scopeValue("validate$data",{ref:a.validateSchema});return(0,O._)`!${d}(${r})`}return O.nil}}subschema(t,r){let n=(0,Ld.getSubschema)(this.it,t);(0,Ld.extendSubschemaData)(n,this.it,t),(0,Ld.extendSubschemaMode)(n,t);let a={...this.it,...n,items:void 0,props:void 0};return AT(a,r),a}mergeEvaluated(t,r){let{it:n,gen:a}=this;n.opts.unevaluated&&(n.props!==!0&&t.props!==void 0&&(n.props=er.mergeEvaluated.props(a,t.props,n.props,r)),n.items!==!0&&t.items!==void 0&&(n.items=er.mergeEvaluated.items(a,t.items,n.items,r)))}mergeValidEvaluated(t,r){let{it:n,gen:a}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return a.if(r,()=>this.mergeEvaluated(t,O.Name)),!0}};Tr.KeywordCxt=ts;function Ry(e,t,r,n){let a=new ts(e,r,t);"code"in r?r.code(a,n):a.$data&&r.validate?(0,ga.funcKeywordCode)(a,r):"macro"in r?(0,ga.macroKeywordCode)(a,r):(r.compile||r.validate)&&(0,ga.funcKeywordCode)(a,r)}o(Ry,"keywordCode");var GT=/^\/(?:[^~]|~0|~1)*$/,VT=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function Cy(e,{dataLevel:t,dataNames:r,dataPathArr:n}){let a,i;if(e==="")return H.default.rootData;if(e[0]==="/"){if(!GT.test(e))throw new Error(`Invalid JSON-pointer: ${e}`);a=e,i=H.default.rootData}else{let p=VT.exec(e);if(!p)throw new Error(`Invalid JSON-pointer: ${e}`);let l=+p[1];if(a=p[2],a==="#"){if(l>=t)throw new Error(d("property/index",l));return n[t-l]}if(l>t)throw new Error(d("data",l));if(i=r[t-l],!a)return i}let s=i,c=a.split("/");for(let p of c)p&&(i=(0,O._)`${i}${(0,O.getProperty)((0,er.unescapeJsonPointer)(p))}`,s=(0,O._)`${s} && ${i}`);return s;function d(p,l){return`Cannot access ${p} ${l} levels up, current level is ${t}`}}o(Cy,"getData");Tr.getData=Cy});var rs=k(Fd=>{"use strict";Object.defineProperty(Fd,"__esModule",{value:!0});var Vd=class extends Error{static{o(this,"ValidationError")}constructor(t){super("validation failed"),this.errors=t,this.ajv=this.validation=!0}};Fd.default=Vd});var Sa=k(Jd=>{"use strict";Object.defineProperty(Jd,"__esModule",{value:!0});var Zd=fa(),Kd=class extends Error{static{o(this,"MissingRefError")}constructor(t,r,n,a){super(a||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Zd.resolveUrl)(t,r,n),this.missingSchema=(0,Zd.normalizeId)((0,Zd.getFullPath)(t,this.missingRef))}};Jd.default=Kd});var os=k(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.resolveSchema=yt.getCompilingSchema=yt.resolveRef=yt.compileSchema=yt.SchemaEnv=void 0;var Rt=F(),FT=rs(),an=Xt(),Ct=fa(),Iy=te(),ZT=ya(),Qn=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,Ct.normalizeId)(n?.[t.schemaId||"$id"]),this.schemaPath=t.schemaPath,this.localRefs=t.localRefs,this.meta=t.meta,this.$async=n?.$async,this.refs={}}};yt.SchemaEnv=Qn;function Yd(e){let t=Py.call(this,e);if(t)return t;let r=(0,Ct.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:n,lines:a}=this.opts.code,{ownProperties:i}=this.opts,s=new Rt.CodeGen(this.scope,{es5:n,lines:a,ownProperties:i}),c;e.$async&&(c=s.scopeValue("Error",{ref:FT.default,code:(0,Rt._)`require("ajv/dist/runtime/validation_error").default`}));let d=s.scopeName("validate");e.validateName=d;let p={gen:s,allErrors:this.opts.allErrors,data:an.default.data,parentData:an.default.parentData,parentDataProperty:an.default.parentDataProperty,dataNames:[an.default.data],dataPathArr:[Rt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:s.scopeValue("schema",this.opts.code.source===!0?{ref:e.schema,code:(0,Rt.stringify)(e.schema)}:{ref:e.schema}),validateName:d,ValidationError:c,schema:e.schema,schemaEnv:e,rootId:r,baseId:e.baseId||r,schemaPath:Rt.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Rt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(e),(0,ZT.validateFunctionCode)(p),s.optimize(this.opts.code.optimize);let m=s.toString();l=`${s.scopeRefs(an.default.scope)}return ${m}`,this.opts.code.process&&(l=this.opts.code.process(l,e));let y=new Function(`${an.default.self}`,`${an.default.scope}`,l)(this,this.scope.get());if(this.scope.value(d,{ref:y}),y.errors=null,y.schema=e.schema,y.schemaEnv=e,e.$async&&(y.$async=!0),this.opts.code.source===!0&&(y.source={validateName:d,validateCode:m,scopeValues:s._values}),this.opts.unevaluated){let{props:v,items:S}=p;y.evaluated={props:v instanceof Rt.Name?void 0:v,items:S instanceof Rt.Name?void 0:S,dynamicProps:v instanceof Rt.Name,dynamicItems:S instanceof Rt.Name},y.source&&(y.source.evaluated=(0,Rt.stringify)(y.evaluated))}return e.validate=y,e}catch(m){throw delete e.validate,delete e.validateName,l&&this.logger.error("Error compiling schema, function code:",l),m}finally{this._compilations.delete(e)}}o(Yd,"compileSchema");yt.compileSchema=Yd;function KT(e,t,r){var n;r=(0,Ct.resolveUrl)(this.opts.uriResolver,t,r);let a=e.refs[r];if(a)return a;let i=YT.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 Qn({schema:s,schemaId:c,root:e,baseId:t}))}if(i!==void 0)return e.refs[r]=JT.call(this,i)}o(KT,"resolveRef");yt.resolveRef=KT;function JT(e){return(0,Ct.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:Yd.call(this,e)}o(JT,"inlineOrCompile");function Py(e){for(let t of this._compilations)if(WT(t,e))return t}o(Py,"getCompilingSchema");yt.getCompilingSchema=Py;function WT(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}o(WT,"sameSchemaEnv");function YT(e,t){let r;for(;typeof(r=this.refs[t])=="string";)t=r;return r||this.schemas[t]||ns.call(this,e,t)}o(YT,"resolve");function ns(e,t){let r=this.opts.uriResolver.parse(t),n=(0,Ct._getFullPath)(this.opts.uriResolver,r),a=(0,Ct.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&n===a)return Wd.call(this,r,e);let i=(0,Ct.normalizeId)(n),s=this.refs[i]||this.schemas[i];if(typeof s=="string"){let c=ns.call(this,e,s);return typeof c?.schema!="object"?void 0:Wd.call(this,r,c)}if(typeof s?.schema=="object"){if(s.validate||Yd.call(this,s),i===(0,Ct.normalizeId)(t)){let{schema:c}=s,{schemaId:d}=this.opts,p=c[d];return p&&(a=(0,Ct.resolveUrl)(this.opts.uriResolver,a,p)),new Qn({schema:c,schemaId:d,root:e,baseId:a})}return Wd.call(this,r,s)}}o(ns,"resolveSchema");yt.resolveSchema=ns;var QT=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Wd(e,{baseId:t,schema:r,root:n}){var a;if(((a=e.fragment)===null||a===void 0?void 0:a[0])!=="/")return;for(let c of e.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let d=r[(0,Iy.unescapeFragment)(c)];if(d===void 0)return;r=d;let p=typeof r=="object"&&r[this.opts.schemaId];!QT.has(c)&&p&&(t=(0,Ct.resolveUrl)(this.opts.uriResolver,t,p))}let i;if(typeof r!="boolean"&&r.$ref&&!(0,Iy.schemaHasRulesButRef)(r,this.RULES)){let c=(0,Ct.resolveUrl)(this.opts.uriResolver,t,r.$ref);i=ns.call(this,n,c)}let{schemaId:s}=this.opts;if(i=i||new Qn({schema:r,schemaId:s,root:n,baseId:t}),i.schema!==i.root.schema)return i}o(Wd,"getJsonPointer")});var xy=k(($9,XT)=>{XT.exports={$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON AnySchema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Xd=k((M9,Ey)=>{"use strict";var eA=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ty=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function Qd(e){let t="",r=0,n=0;for(n=0;n<e.length;n++)if(r=e[n].charCodeAt(0),r!==48){if(!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n];break}for(n+=1;n<e.length;n++){if(r=e[n].charCodeAt(0),!(r>=48&&r<=57||r>=65&&r<=70||r>=97&&r<=102))return"";t+=e[n]}return t}o(Qd,"stringArrayToHexStripped");var tA=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function ky(e){return e.length=0,!0}o(ky,"consumeIsZone");function rA(e,t,r){if(e.length){let n=Qd(e);if(n!=="")t.push(n);else return r.error=!0,!1;e.length=0}return!0}o(rA,"consumeHextets");function nA(e){let t=0,r={error:!1,address:"",zone:""},n=[],a=[],i=!1,s=!1,c=rA;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(Qd(a))),r.address=n.join(""),r}o(nA,"getIPV6");function Ay(e){if(oA(e,":")<2)return{host:e,isIPV6:!1};let t=nA(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(Ay,"normalizeIPv6");function oA(e,t){let r=0;for(let n=0;n<e.length;n++)e[n]===t&&r++;return r}o(oA,"findToken");function aA(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(aA,"removeDotSegments");function iA(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(iA,"normalizeComponentEncoding");function sA(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push("@")),e.host!==void 0){let r=unescape(e.host);if(!Ty(r)){let n=Ay(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(sA,"recomposeAuthority");Ey.exports={nonSimpleDomain:tA,recomposeAuthority:sA,normalizeComponentEncoding:iA,removeDotSegments:aA,isIPv4:Ty,isUUID:eA,normalizeIPv6:Ay,stringArrayToHexStripped:Qd}});var zy=k((q9,My)=>{"use strict";var{isUUID:cA}=Xd(),uA=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,dA=["http","https","ws","wss","urn","urn:uuid"];function lA(e){return dA.indexOf(e)!==-1}o(lA,"isValidSchemeName");function el(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]==="w"||e.scheme[0]==="W")&&(e.scheme[1]==="s"||e.scheme[1]==="S")&&(e.scheme[2]==="s"||e.scheme[2]==="S"):!1}o(el,"wsIsSecure");function Uy(e){return e.host||(e.error=e.error||"HTTP URIs must have a host."),e}o(Uy,"httpParse");function Oy(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(Oy,"httpSerialize");function pA(e){return e.secure=el(e),e.resourceName=(e.path||"/")+(e.query?"?"+e.query:""),e.path=void 0,e.query=void 0,e}o(pA,"wsParse");function mA(e){if((e.port===(el(e)?443:80)||e.port==="")&&(e.port=void 0),typeof e.secure=="boolean"&&(e.scheme=e.secure?"wss":"ws",e.secure=void 0),e.resourceName){let[t,r]=e.resourceName.split("?");e.path=t&&t!=="/"?t:void 0,e.query=r,e.resourceName=void 0}return e.fragment=void 0,e}o(mA,"wsSerialize");function fA(e,t){if(!e.path)return e.error="URN can not be parsed",e;let r=e.path.match(uA);if(r){let n=t.scheme||e.scheme||"urn";e.nid=r[1].toLowerCase(),e.nss=r[2];let a=`${n}:${t.nid||e.nid}`,i=tl(a);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||"URN can not be parsed.";return e}o(fA,"urnParse");function hA(e,t){if(e.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=t.scheme||e.scheme||"urn",n=e.nid.toLowerCase(),a=`${r}:${t.nid||n}`,i=tl(a);i&&(e=i.serialize(e,t));let s=e,c=e.nss;return s.path=`${n||t.nid}:${c}`,t.skipEscape=!0,s}o(hA,"urnSerialize");function gA(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!cA(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}o(gA,"urnuuidParse");function yA(e){let t=e;return t.nss=(e.uuid||"").toLowerCase(),t}o(yA,"urnuuidSerialize");var $y={scheme:"http",domainHost:!0,parse:Uy,serialize:Oy},SA={scheme:"https",domainHost:$y.domainHost,parse:Uy,serialize:Oy},as={scheme:"ws",domainHost:!0,parse:pA,serialize:mA},vA={scheme:"wss",domainHost:as.domainHost,parse:as.parse,serialize:as.serialize},_A={scheme:"urn",parse:fA,serialize:hA,skipNormalize:!0},wA={scheme:"urn:uuid",parse:gA,serialize:yA,skipNormalize:!0},is={http:$y,https:SA,ws:as,wss:vA,urn:_A,"urn:uuid":wA};Object.setPrototypeOf(is,null);function tl(e){return e&&(is[e]||is[e.toLowerCase()])||void 0}o(tl,"getSchemeHandler");My.exports={wsIsSecure:el,SCHEMES:is,isValidSchemeName:lA,getSchemeHandler:tl}});var jy=k((j9,cs)=>{"use strict";var{normalizeIPv6:bA,removeDotSegments:va,recomposeAuthority:RA,normalizeComponentEncoding:ss,isIPv4:CA,nonSimpleDomain:IA}=Xd(),{SCHEMES:PA,getSchemeHandler:qy}=zy();function xA(e,t){return typeof e=="string"?e=$t(tr(e,t),t):typeof e=="object"&&(e=tr($t(e,t),t)),e}o(xA,"normalize");function kA(e,t,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},a=Ny(tr(e,n),tr(t,n),n,!0);return n.skipEscape=!0,$t(a,n)}o(kA,"resolve");function Ny(e,t,r,n){let a={};return n||(e=tr($t(e,r),r),t=tr($t(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=va(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=va(t.path||""),a.query=t.query):(t.path?(t.path[0]==="/"?a.path=va(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=va(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(Ny,"resolveComponent");function TA(e,t,r){return typeof e=="string"?(e=unescape(e),e=$t(ss(tr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=$t(ss(e,!0),{...r,skipEscape:!0})),typeof t=="string"?(t=unescape(t),t=$t(ss(tr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=$t(ss(t,!0),{...r,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}o(TA,"equal");function $t(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=qy(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=RA(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=va(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($t,"serialize");var AA=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function tr(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(AA);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(CA(n.host)===!1){let d=bA(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=qy(r.scheme||n.scheme);if(!r.unicodeSupport&&(!s||!s.unicodeSupport)&&n.host&&(r.domainHost||s&&s.domainHost)&&a===!1&&IA(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(tr,"parse");var rl={SCHEMES:PA,normalize:xA,resolve:kA,resolveComponent:Ny,equal:TA,serialize:$t,parse:tr};cs.exports=rl;cs.exports.default=rl;cs.exports.fastUri=rl});var Hy=k(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});var Dy=jy();Dy.code='require("ajv/dist/runtime/uri").default';nl.default=Dy});var Jy=k(ze=>{"use strict";Object.defineProperty(ze,"__esModule",{value:!0});ze.CodeGen=ze.Name=ze.nil=ze.stringify=ze.str=ze._=ze.KeywordCxt=void 0;var EA=ya();Object.defineProperty(ze,"KeywordCxt",{enumerable:!0,get:o(function(){return EA.KeywordCxt},"get")});var Xn=F();Object.defineProperty(ze,"_",{enumerable:!0,get:o(function(){return Xn._},"get")});Object.defineProperty(ze,"str",{enumerable:!0,get:o(function(){return Xn.str},"get")});Object.defineProperty(ze,"stringify",{enumerable:!0,get:o(function(){return Xn.stringify},"get")});Object.defineProperty(ze,"nil",{enumerable:!0,get:o(function(){return Xn.nil},"get")});Object.defineProperty(ze,"Name",{enumerable:!0,get:o(function(){return Xn.Name},"get")});Object.defineProperty(ze,"CodeGen",{enumerable:!0,get:o(function(){return Xn.CodeGen},"get")});var UA=rs(),Fy=Sa(),OA=Ud(),_a=os(),$A=F(),wa=fa(),us=ma(),al=te(),Ly=xy(),MA=Hy(),Zy=o((e,t)=>new RegExp(e,t),"defaultRegExp");Zy.code="new RegExp";var zA=["removeAdditional","useDefaults","coerceTypes"],qA=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),NA={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."},jA={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},By=200;function DA(e){var t,r,n,a,i,s,c,d,p,l,m,h,y,v,S,_,w,b,R,z,q,je,ut,wn,sr;let Dt=e.strict,qr=(t=e.code)===null||t===void 0?void 0:t.optimize,ho=qr===!0||qr===void 0?1:qr||0,go=(n=(r=e.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Zy,yo=(a=e.uriResolver)!==null&&a!==void 0?a:MA.default;return{strictSchema:(s=(i=e.strictSchema)!==null&&i!==void 0?i:Dt)!==null&&s!==void 0?s:!0,strictNumbers:(d=(c=e.strictNumbers)!==null&&c!==void 0?c:Dt)!==null&&d!==void 0?d:!0,strictTypes:(l=(p=e.strictTypes)!==null&&p!==void 0?p:Dt)!==null&&l!==void 0?l:"log",strictTuples:(h=(m=e.strictTuples)!==null&&m!==void 0?m:Dt)!==null&&h!==void 0?h:"log",strictRequired:(v=(y=e.strictRequired)!==null&&y!==void 0?y:Dt)!==null&&v!==void 0?v:!1,code:e.code?{...e.code,optimize:ho,regExp:go}:{optimize:ho,regExp:go},loopRequired:(S=e.loopRequired)!==null&&S!==void 0?S:By,loopEnum:(_=e.loopEnum)!==null&&_!==void 0?_:By,meta:(w=e.meta)!==null&&w!==void 0?w:!0,messages:(b=e.messages)!==null&&b!==void 0?b:!0,inlineRefs:(R=e.inlineRefs)!==null&&R!==void 0?R:!0,schemaId:(z=e.schemaId)!==null&&z!==void 0?z:"$id",addUsedSchema:(q=e.addUsedSchema)!==null&&q!==void 0?q:!0,validateSchema:(je=e.validateSchema)!==null&&je!==void 0?je:!0,validateFormats:(ut=e.validateFormats)!==null&&ut!==void 0?ut:!0,unicodeRegExp:(wn=e.unicodeRegExp)!==null&&wn!==void 0?wn:!0,int32range:(sr=e.int32range)!==null&&sr!==void 0?sr:!0,uriResolver:yo}}o(DA,"requiredOptions");var ba=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,...DA(t)};let{es5:r,lines:n}=this.opts.code;this.scope=new $A.ValueScope({scope:{},prefixes:qA,es5:r,lines:n}),this.logger=FA(t.logger);let a=t.validateFormats;t.validateFormats=!1,this.RULES=(0,OA.getRules)(),Gy.call(this,NA,t,"NOT SUPPORTED"),Gy.call(this,jA,t,"DEPRECATED","warn"),this._metaOpts=GA.call(this),t.formats&&LA.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),t.keywords&&BA.call(this,t.keywords),typeof t.meta=="object"&&this.addMetaSchema(t.meta),HA.call(this),t.validateFormats=a}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:t,meta:r,schemaId:n}=this.opts,a=Ly;n==="id"&&(a={...Ly},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 Fy.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,wa.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=Vy.call(this,t))=="string";)t=r;if(r===void 0){let{schemaId:n}=this.opts,a=new _a.SchemaEnv({schema:{},schemaId:n});if(r=_a.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=Vy.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,wa.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(KA.call(this,n,r),!r)return(0,al.eachItem)(n,i=>ol.call(this,i)),this;WA.call(this,r);let a={...r,type:(0,us.getJSONTypes)(r.type),schemaType:(0,us.getJSONTypes)(r.schemaType)};return(0,al.eachItem)(n,a.type.length===0?i=>ol.call(this,i,a):i=>a.type.forEach(s=>ol.call(this,i,a,s))),this}getKeyword(t){let r=this.RULES.all[t];return typeof r=="object"?r.definition:!!r}removeKeyword(t){let{RULES:r}=this;delete r.keywords[t],delete r.all[t];for(let n of r.rules){let a=n.rules.findIndex(i=>i.keyword===t);a>=0&&n.rules.splice(a,1)}return this}addFormat(t,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[t]=r,this}errorsText(t=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!t||t.length===0?"No errors":t.map(a=>`${n}${a.instancePath} ${a.message}`).reduce((a,i)=>a+r+i)}$dataMetaSchema(t,r){let n=this.RULES.all;t=JSON.parse(JSON.stringify(t));for(let a of r){let i=a.split("/").slice(1),s=t;for(let c of i)s=s[c];for(let c in n){let d=n[c];if(typeof d!="object")continue;let{$data:p}=d.definition,l=s[c];p&&l&&(s[c]=Ky(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,wa.normalizeId)(s||n);let p=wa.getSchemaRefs.call(this,t,n);return d=new _a.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):_a.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{_a.compileSchema.call(this,t)}finally{this.opts=r}}};ba.ValidationError=UA.default;ba.MissingRefError=Fy.default;ze.default=ba;function Gy(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(Gy,"checkOptions");function Vy(e){return e=(0,wa.normalizeId)(e),this.schemas[e]||this.refs[e]}o(Vy,"getSchEnv");function HA(){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(HA,"addInitialSchemas");function LA(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}o(LA,"addInitialFormats");function BA(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(BA,"addInitialKeywords");function GA(){let e={...this.opts};for(let t of zA)delete e[t];return e}o(GA,"getMetaSchemaOptions");var VA={log(){},warn(){},error(){}};function FA(e){if(e===!1)return VA;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(FA,"getLogger");var ZA=/^[a-z_$][a-z0-9_$:-]*$/i;function KA(e,t){let{RULES:r}=this;if((0,al.eachItem)(e,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!ZA.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(KA,"checkKeyword");function ol(e,t,r){var n;let a=t?.post;if(r&&a)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:i}=this,s=a?i.post:i.rules.find(({type:d})=>d===r);if(s||(s={type:r,rules:[]},i.rules.push(s)),i.keywords[e]=!0,!t)return;let c={keyword:e,definition:{...t,type:(0,us.getJSONTypes)(t.type),schemaType:(0,us.getJSONTypes)(t.schemaType)}};t.before?JA.call(this,s,c,t.before):s.rules.push(c),i.all[e]=c,(n=t.implements)===null||n===void 0||n.forEach(d=>this.addKeyword(d))}o(ol,"addRule");function JA(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(JA,"addBeforeRule");function WA(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=Ky(t)),e.validateSchema=this.compile(t,!0))}o(WA,"keywordMetaschema");var YA={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Ky(e){return{anyOf:[e,YA]}}o(Ky,"schemaOrData")});var Wy=k(il=>{"use strict";Object.defineProperty(il,"__esModule",{value:!0});var QA={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};il.default=QA});var eS=k(sn=>{"use strict";Object.defineProperty(sn,"__esModule",{value:!0});sn.callRef=sn.getValidate=void 0;var XA=Sa(),Yy=gt(),rt=F(),eo=Xt(),Qy=os(),ds=te(),e0={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=Qy.resolveRef.call(d,p,a,r);if(l===void 0)throw new XA.default(n.opts.uriResolver,a,r);if(l instanceof Qy.SchemaEnv)return h(l);return y(l);function m(){if(i===p)return ls(e,s,i,i.$async);let v=t.scopeValue("root",{ref:p});return ls(e,(0,rt._)`${v}.validate`,p,p.$async)}function h(v){let S=Xy(e,v);ls(e,S,v,v.$async)}function y(v){let S=t.scopeValue("schema",c.code.source===!0?{ref:v,code:(0,rt.stringify)(v)}:{ref:v}),_=t.name("valid"),w=e.subschema({schema:v,dataTypes:[],schemaPath:rt.nil,topSchemaRef:S,errSchemaPath:r},_);e.mergeEvaluated(w),e.ok(_)}}};function Xy(e,t){let{gen:r}=e;return t.validate?r.scopeValue("validate",{ref:t.validate}):(0,rt._)`${r.scopeValue("wrapper",{ref:t})}.validate`}o(Xy,"getValidate");sn.getValidate=Xy;function ls(e,t,r,n){let{gen:a,it:i}=e,{allErrors:s,schemaEnv:c,opts:d}=i,p=d.passContext?eo.default.this:rt.nil;n?l():m();function l(){if(!c.$async)throw new Error("async schema referenced by sync schema");let v=a.let("valid");a.try(()=>{a.code((0,rt._)`await ${(0,Yy.callValidateCode)(e,t,p)}`),y(t),s||a.assign(v,!0)},S=>{a.if((0,rt._)`!(${S} instanceof ${i.ValidationError})`,()=>a.throw(S)),h(S),s||a.assign(v,!1)}),e.ok(v)}o(l,"callAsyncRef");function m(){e.result((0,Yy.callValidateCode)(e,t,p),()=>y(t),()=>h(t))}o(m,"callSyncRef");function h(v){let S=(0,rt._)`${v}.errors`;a.assign(eo.default.vErrors,(0,rt._)`${eo.default.vErrors} === null ? ${S} : ${eo.default.vErrors}.concat(${S})`),a.assign(eo.default.errors,(0,rt._)`${eo.default.vErrors}.length`)}o(h,"addErrorsFrom");function y(v){var S;if(!i.opts.unevaluated)return;let _=(S=r?.validate)===null||S===void 0?void 0:S.evaluated;if(i.props!==!0)if(_&&!_.dynamicProps)_.props!==void 0&&(i.props=ds.mergeEvaluated.props(a,_.props,i.props));else{let w=a.var("props",(0,rt._)`${v}.evaluated.props`);i.props=ds.mergeEvaluated.props(a,w,i.props,rt.Name)}if(i.items!==!0)if(_&&!_.dynamicItems)_.items!==void 0&&(i.items=ds.mergeEvaluated.items(a,_.items,i.items));else{let w=a.var("items",(0,rt._)`${v}.evaluated.items`);i.items=ds.mergeEvaluated.items(a,w,i.items,rt.Name)}}o(y,"addEvaluatedFrom")}o(ls,"callRef");sn.callRef=ls;sn.default=e0});var tS=k(sl=>{"use strict";Object.defineProperty(sl,"__esModule",{value:!0});var t0=Wy(),r0=eS(),n0=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",t0.default,r0.default];sl.default=n0});var rS=k(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});var ps=F(),Ar=ps.operators,ms={maximum:{okStr:"<=",ok:Ar.LTE,fail:Ar.GT},minimum:{okStr:">=",ok:Ar.GTE,fail:Ar.LT},exclusiveMaximum:{okStr:"<",ok:Ar.LT,fail:Ar.GTE},exclusiveMinimum:{okStr:">",ok:Ar.GT,fail:Ar.LTE}},o0={message:o(({keyword:e,schemaCode:t})=>(0,ps.str)`must be ${ms[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,ps._)`{comparison: ${ms[e].okStr}, limit: ${t}}`,"params")},a0={keyword:Object.keys(ms),type:"number",schemaType:"number",$data:!0,error:o0,code(e){let{keyword:t,data:r,schemaCode:n}=e;e.fail$data((0,ps._)`${r} ${ms[t].fail} ${n} || isNaN(${r})`)}};cl.default=a0});var nS=k(ul=>{"use strict";Object.defineProperty(ul,"__esModule",{value:!0});var Ra=F(),i0={message:o(({schemaCode:e})=>(0,Ra.str)`must be multiple of ${e}`,"message"),params:o(({schemaCode:e})=>(0,Ra._)`{multipleOf: ${e}}`,"params")},s0={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:i0,code(e){let{gen:t,data:r,schemaCode:n,it:a}=e,i=a.opts.multipleOfPrecision,s=t.let("res"),c=i?(0,Ra._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${i}`:(0,Ra._)`${s} !== parseInt(${s})`;e.fail$data((0,Ra._)`(${n} === 0 || (${s} = ${r}/${n}, ${c}))`)}};ul.default=s0});var aS=k(dl=>{"use strict";Object.defineProperty(dl,"__esModule",{value:!0});function oS(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(oS,"ucs2length");dl.default=oS;oS.code='require("ajv/dist/runtime/ucs2length").default'});var iS=k(ll=>{"use strict";Object.defineProperty(ll,"__esModule",{value:!0});var cn=F(),c0=te(),u0=aS(),d0={message({keyword:e,schemaCode:t}){let r=e==="maxLength"?"more":"fewer";return(0,cn.str)`must NOT have ${r} than ${t} characters`},params:o(({schemaCode:e})=>(0,cn._)`{limit: ${e}}`,"params")},l0={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:d0,code(e){let{keyword:t,data:r,schemaCode:n,it:a}=e,i=t==="maxLength"?cn.operators.GT:cn.operators.LT,s=a.opts.unicode===!1?(0,cn._)`${r}.length`:(0,cn._)`${(0,c0.useFunc)(e.gen,u0.default)}(${r})`;e.fail$data((0,cn._)`${s} ${i} ${n}`)}};ll.default=l0});var sS=k(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});var p0=gt(),fs=F(),m0={message:o(({schemaCode:e})=>(0,fs.str)`must match pattern "${e}"`,"message"),params:o(({schemaCode:e})=>(0,fs._)`{pattern: ${e}}`,"params")},f0={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,fs._)`(new RegExp(${a}, ${s}))`:(0,p0.usePattern)(e,n);e.fail$data((0,fs._)`!${c}.test(${t})`)}};pl.default=f0});var cS=k(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});var Ca=F(),h0={message({keyword:e,schemaCode:t}){let r=e==="maxProperties"?"more":"fewer";return(0,Ca.str)`must NOT have ${r} than ${t} properties`},params:o(({schemaCode:e})=>(0,Ca._)`{limit: ${e}}`,"params")},g0={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:h0,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxProperties"?Ca.operators.GT:Ca.operators.LT;e.fail$data((0,Ca._)`Object.keys(${r}).length ${a} ${n}`)}};ml.default=g0});var uS=k(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});var Ia=gt(),Pa=F(),y0=te(),S0={message:o(({params:{missingProperty:e}})=>(0,Pa.str)`must have required property '${e}'`,"message"),params:o(({params:{missingProperty:e}})=>(0,Pa._)`{missingProperty: ${e}}`,"params")},v0={keyword:"required",type:"object",schemaType:"array",$data:!0,error:S0,code(e){let{gen:t,schema:r,schemaCode:n,data:a,$data:i,it:s}=e,{opts:c}=s;if(!i&&r.length===0)return;let d=r.length>=c.loopRequired;if(s.allErrors?p():l(),c.strictRequired){let y=e.parentSchema.properties,{definedProperties:v}=e.it;for(let S of r)if(y?.[S]===void 0&&!v.has(S)){let _=s.schemaEnv.baseId+s.errSchemaPath,w=`required property "${S}" is not defined at "${_}" (strictRequired)`;(0,y0.checkStrictMode)(s,w,s.opts.strictRequired)}}function p(){if(d||i)e.block$data(Pa.nil,m);else for(let y of r)(0,Ia.checkReportMissingProp)(e,y)}o(p,"allErrorsMode");function l(){let y=t.let("missing");if(d||i){let v=t.let("valid",!0);e.block$data(v,()=>h(y,v)),e.ok(v)}else t.if((0,Ia.checkMissingProp)(e,r,y)),(0,Ia.reportMissingProp)(e,y),t.else()}o(l,"exitOnErrorMode");function m(){t.forOf("prop",n,y=>{e.setParams({missingProperty:y}),t.if((0,Ia.noPropertyInData)(t,a,y,c.ownProperties),()=>e.error())})}o(m,"loopAllRequired");function h(y,v){e.setParams({missingProperty:y}),t.forOf(y,n,()=>{t.assign(v,(0,Ia.propertyInData)(t,a,y,c.ownProperties)),t.if((0,Pa.not)(v),()=>{e.error(),t.break()})},Pa.nil)}o(h,"loopUntilMissing")}};fl.default=v0});var dS=k(hl=>{"use strict";Object.defineProperty(hl,"__esModule",{value:!0});var xa=F(),_0={message({keyword:e,schemaCode:t}){let r=e==="maxItems"?"more":"fewer";return(0,xa.str)`must NOT have ${r} than ${t} items`},params:o(({schemaCode:e})=>(0,xa._)`{limit: ${e}}`,"params")},w0={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:_0,code(e){let{keyword:t,data:r,schemaCode:n}=e,a=t==="maxItems"?xa.operators.GT:xa.operators.LT;e.fail$data((0,xa._)`${r}.length ${a} ${n}`)}};hl.default=w0});var hs=k(gl=>{"use strict";Object.defineProperty(gl,"__esModule",{value:!0});var lS=Dd();lS.code='require("ajv/dist/runtime/equal").default';gl.default=lS});var pS=k(Sl=>{"use strict";Object.defineProperty(Sl,"__esModule",{value:!0});var yl=ma(),qe=F(),b0=te(),R0=hs(),C0={message:o(({params:{i:e,j:t}})=>(0,qe.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,"message"),params:o(({params:{i:e,j:t}})=>(0,qe._)`{i: ${e}, j: ${t}}`,"params")},I0={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:C0,code(e){let{gen:t,data:r,$data:n,schema:a,parentSchema:i,schemaCode:s,it:c}=e;if(!n&&!a)return;let d=t.let("valid"),p=i.items?(0,yl.getSchemaTypes)(i.items):[];e.block$data(d,l,(0,qe._)`${s} === false`),e.ok(d);function l(){let v=t.let("i",(0,qe._)`${r}.length`),S=t.let("j");e.setParams({i:v,j:S}),t.assign(d,!0),t.if((0,qe._)`${v} > 1`,()=>(m()?h:y)(v,S))}o(l,"validateUniqueItems");function m(){return p.length>0&&!p.some(v=>v==="object"||v==="array")}o(m,"canOptimize");function h(v,S){let _=t.name("item"),w=(0,yl.checkDataTypes)(p,_,c.opts.strictNumbers,yl.DataType.Wrong),b=t.const("indices",(0,qe._)`{}`);t.for((0,qe._)`;${v}--;`,()=>{t.let(_,(0,qe._)`${r}[${v}]`),t.if(w,(0,qe._)`continue`),p.length>1&&t.if((0,qe._)`typeof ${_} == "string"`,(0,qe._)`${_} += "_"`),t.if((0,qe._)`typeof ${b}[${_}] == "number"`,()=>{t.assign(S,(0,qe._)`${b}[${_}]`),e.error(),t.assign(d,!1).break()}).code((0,qe._)`${b}[${_}] = ${v}`)})}o(h,"loopN");function y(v,S){let _=(0,b0.useFunc)(t,R0.default),w=t.name("outer");t.label(w).for((0,qe._)`;${v}--;`,()=>t.for((0,qe._)`${S} = ${v}; ${S}--;`,()=>t.if((0,qe._)`${_}(${r}[${v}], ${r}[${S}])`,()=>{e.error(),t.assign(d,!1).break(w)})))}o(y,"loopN2")}};Sl.default=I0});var mS=k(_l=>{"use strict";Object.defineProperty(_l,"__esModule",{value:!0});var vl=F(),P0=te(),x0=hs(),k0={message:"must be equal to constant",params:o(({schemaCode:e})=>(0,vl._)`{allowedValue: ${e}}`,"params")},T0={keyword:"const",$data:!0,error:k0,code(e){let{gen:t,data:r,$data:n,schemaCode:a,schema:i}=e;n||i&&typeof i=="object"?e.fail$data((0,vl._)`!${(0,P0.useFunc)(t,x0.default)}(${r}, ${a})`):e.fail((0,vl._)`${i} !== ${r}`)}};_l.default=T0});var fS=k(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});var ka=F(),A0=te(),E0=hs(),U0={message:"must be equal to one of the allowed values",params:o(({schemaCode:e})=>(0,ka._)`{allowedValues: ${e}}`,"params")},O0={keyword:"enum",schemaType:"array",$data:!0,error:U0,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,A0.useFunc)(t,E0.default)),"getEql"),l;if(c||n)l=t.let("valid"),e.block$data(l,m);else{if(!Array.isArray(a))throw new Error("ajv implementation error");let y=t.const("vSchema",i);l=(0,ka.or)(...a.map((v,S)=>h(y,S)))}e.pass(l);function m(){t.assign(l,!1),t.forOf("v",i,y=>t.if((0,ka._)`${p()}(${r}, ${y})`,()=>t.assign(l,!0).break()))}o(m,"loopEnum");function h(y,v){let S=a[v];return typeof S=="object"&&S!==null?(0,ka._)`${p()}(${r}, ${y}[${v}])`:(0,ka._)`${r} === ${S}`}o(h,"equalCode")}};wl.default=O0});var hS=k(bl=>{"use strict";Object.defineProperty(bl,"__esModule",{value:!0});var $0=rS(),M0=nS(),z0=iS(),q0=sS(),N0=cS(),j0=uS(),D0=dS(),H0=pS(),L0=mS(),B0=fS(),G0=[$0.default,M0.default,z0.default,q0.default,N0.default,j0.default,D0.default,H0.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},L0.default,B0.default];bl.default=G0});var Cl=k(Ta=>{"use strict";Object.defineProperty(Ta,"__esModule",{value:!0});Ta.validateAdditionalItems=void 0;var un=F(),Rl=te(),V0={message:o(({params:{len:e}})=>(0,un.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,un._)`{limit: ${e}}`,"params")},F0={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:V0,code(e){let{parentSchema:t,it:r}=e,{items:n}=t;if(!Array.isArray(n)){(0,Rl.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}gS(e,n)}};function gS(e,t){let{gen:r,schema:n,data:a,keyword:i,it:s}=e;s.items=!0;let c=r.const("len",(0,un._)`${a}.length`);if(n===!1)e.setParams({len:t.length}),e.pass((0,un._)`${c} <= ${t.length}`);else if(typeof n=="object"&&!(0,Rl.alwaysValidSchema)(s,n)){let p=r.var("valid",(0,un._)`${c} <= ${t.length}`);r.if((0,un.not)(p),()=>d(p)),e.ok(p)}function d(p){r.forRange("i",t.length,c,l=>{e.subschema({keyword:i,dataProp:l,dataPropType:Rl.Type.Num},p),s.allErrors||r.if((0,un.not)(p),()=>r.break())})}o(d,"validateItems")}o(gS,"validateAdditionalItems");Ta.validateAdditionalItems=gS;Ta.default=F0});var Il=k(Aa=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});Aa.validateTuple=void 0;var yS=F(),gs=te(),Z0=gt(),K0={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(e){let{schema:t,it:r}=e;if(Array.isArray(t))return SS(e,"additionalItems",t);r.items=!0,!(0,gs.alwaysValidSchema)(r,t)&&e.ok((0,Z0.validateArray)(e))}};function SS(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=gs.mergeEvaluated.items(n,r.length,c.items));let d=n.name("valid"),p=n.const("len",(0,yS._)`${i}.length`);r.forEach((m,h)=>{(0,gs.alwaysValidSchema)(c,m)||(n.if((0,yS._)`${p} > ${h}`,()=>e.subschema({keyword:s,schemaProp:h,dataProp:h},d)),e.ok(d))});function l(m){let{opts:h,errSchemaPath:y}=c,v=r.length,S=v===m.minItems&&(v===m.maxItems||m[t]===!1);if(h.strictTuples&&!S){let _=`"${s}" is ${v}-tuple, but minItems or maxItems/${t} are not specified or different at path "${y}"`;(0,gs.checkStrictMode)(c,_,h.strictTuples)}}o(l,"checkStrictTuple")}o(SS,"validateTuple");Aa.validateTuple=SS;Aa.default=K0});var vS=k(Pl=>{"use strict";Object.defineProperty(Pl,"__esModule",{value:!0});var J0=Il(),W0={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:o(e=>(0,J0.validateTuple)(e,"items"),"code")};Pl.default=W0});var wS=k(xl=>{"use strict";Object.defineProperty(xl,"__esModule",{value:!0});var _S=F(),Y0=te(),Q0=gt(),X0=Cl(),eE={message:o(({params:{len:e}})=>(0,_S.str)`must NOT have more than ${e} items`,"message"),params:o(({params:{len:e}})=>(0,_S._)`{limit: ${e}}`,"params")},tE={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:eE,code(e){let{schema:t,parentSchema:r,it:n}=e,{prefixItems:a}=r;n.items=!0,!(0,Y0.alwaysValidSchema)(n,t)&&(a?(0,X0.validateAdditionalItems)(e,a):e.ok((0,Q0.validateArray)(e)))}};xl.default=tE});var bS=k(kl=>{"use strict";Object.defineProperty(kl,"__esModule",{value:!0});var St=F(),ys=te(),rE={message:o(({params:{min:e,max:t}})=>t===void 0?(0,St.str)`must contain at least ${e} valid item(s)`:(0,St.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,St._)`{minContains: ${e}}`:(0,St._)`{minContains: ${e}, maxContains: ${t}}`,"params")},nE={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,St._)`${a}.length`);if(e.setParams({min:s,max:c}),c===void 0&&s===0){(0,ys.checkStrictMode)(i,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(c!==void 0&&s>c){(0,ys.checkStrictMode)(i,'"minContains" > "maxContains" is always invalid'),e.fail();return}if((0,ys.alwaysValidSchema)(i,r)){let S=(0,St._)`${l} >= ${s}`;c!==void 0&&(S=(0,St._)`${S} && ${l} <= ${c}`),e.pass(S);return}i.items=!0;let m=t.name("valid");c===void 0&&s===1?y(m,()=>t.if(m,()=>t.break())):s===0?(t.let(m,!0),c!==void 0&&t.if((0,St._)`${a}.length > 0`,h)):(t.let(m,!1),h()),e.result(m,()=>e.reset());function h(){let S=t.name("_valid"),_=t.let("count",0);y(S,()=>t.if(S,()=>v(_)))}o(h,"validateItemsWithCount");function y(S,_){t.forRange("i",0,l,w=>{e.subschema({keyword:"contains",dataProp:w,dataPropType:ys.Type.Num,compositeRule:!0},S),_()})}o(y,"validateItems");function v(S){t.code((0,St._)`${S}++`),c===void 0?t.if((0,St._)`${S} >= ${s}`,()=>t.assign(m,!0).break()):(t.if((0,St._)`${S} > ${c}`,()=>t.assign(m,!1).break()),s===1?t.assign(m,!0):t.if((0,St._)`${S} >= ${s}`,()=>t.assign(m,!0)))}o(v,"checkLimits")}};kl.default=nE});var IS=k(Mt=>{"use strict";Object.defineProperty(Mt,"__esModule",{value:!0});Mt.validateSchemaDeps=Mt.validatePropertyDeps=Mt.error=void 0;var Tl=F(),oE=te(),Ea=gt();Mt.error={message:o(({params:{property:e,depsCount:t,deps:r}})=>{let n=t===1?"property":"properties";return(0,Tl.str)`must have ${n} ${r} when property ${e} is present`},"message"),params:o(({params:{property:e,depsCount:t,deps:r,missingProperty:n}})=>(0,Tl._)`{property: ${e},
|
|
30
30
|
missingProperty: ${n},
|
|
31
31
|
depsCount: ${t},
|
|
32
|
-
deps: ${r}}`,"params")};var Q0={keyword:"dependencies",type:"object",schemaType:"object",error:Et.error,code(e){let[t,r]=X0(e);mS(e,t),fS(e,r)}};function X0({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(X0,"splitDependencies");function mS(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,Ta.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,Ta.checkReportMissingProp)(e,p)}):(r.if((0,Tl._)`${d} && (${(0,Ta.checkMissingProp)(e,c,i)})`),(0,Ta.reportMissingProp)(e,i),r.else())}}o(mS,"validatePropertyDeps");Et.validatePropertyDeps=mS;function fS(e,t=e.schema){let{gen:r,data:n,keyword:a,it:i}=e,s=r.name("valid");for(let c in t)(0,Y0.alwaysValidSchema)(i,t[c])||(r.if((0,Ta.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(fS,"validateSchemaDeps");Et.validateSchemaDeps=fS;Et.default=Q0});var yS=k(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});var gS=F(),eE=te(),tE={message:"property name must be valid",params:o(({params:e})=>(0,gS._)`{propertyName: ${e.propertyName}}`,"params")},rE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:tE,code(e){let{gen:t,schema:r,data:n,it:a}=e;if((0,eE.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,gS.not)(i),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(i)}};Al.default=rE});var Ul=k(El=>{"use strict";Object.defineProperty(El,"__esModule",{value:!0});var hs=pt(),wt=F(),nE=Wt(),gs=te(),oE={message:"must NOT have additional properties",params:o(({params:e})=>(0,wt._)`{additionalProperty: ${e.additionalProperty}}`,"params")},aE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:oE,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,gs.alwaysValidSchema)(s,r))return;let p=(0,hs.allSchemaProperties)(n.properties),l=(0,hs.allSchemaProperties)(n.patternProperties);m(),e.ok((0,wt._)`${i} === ${nE.default.errors}`);function m(){t.forIn("key",a,_=>{!p.length&&!l.length?v(_):t.if(h(_),()=>v(_))})}o(m,"checkAdditionalProperties");function h(_){let w;if(p.length>8){let b=(0,gs.schemaRefOrVal)(s,n.properties,"properties");w=(0,hs.isOwnProperty)(t,b,_)}else p.length?w=(0,wt.or)(...p.map(b=>(0,wt._)`${_} === ${b}`)):w=wt.nil;return l.length&&(w=(0,wt.or)(w,...l.map(b=>(0,wt._)`${(0,hs.usePattern)(e,b)}.test(${_})`))),(0,wt.not)(w)}o(h,"isAdditional");function y(_){t.code((0,wt._)`delete ${a}[${_}]`)}o(y,"deleteAdditional");function v(_){if(d.removeAdditional==="all"||d.removeAdditional&&r===!1){y(_);return}if(r===!1){e.setParams({additionalProperty:_}),e.error(),c||t.break();return}if(typeof r=="object"&&!(0,gs.alwaysValidSchema)(s,r)){let w=t.name("valid");d.removeAdditional==="failing"?(S(_,w,!1),t.if((0,wt.not)(w),()=>{e.reset(),y(_)})):(S(_,w),c||t.if((0,wt.not)(w),()=>t.break()))}}o(v,"additionalPropertyCode");function S(_,w,b){let R={keyword:"additionalProperties",dataProp:_,dataPropType:gs.Type.Str};b===!1&&Object.assign(R,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(R,w)}o(S,"applyAdditionalSchema")}};El.default=aE});var _S=k($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});var iE=ha(),SS=pt(),Ol=te(),vS=Ul(),sE={keyword:"properties",type:"object",schemaType:"object",code(e){let{gen:t,schema:r,parentSchema:n,data:a,it:i}=e;i.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&vS.default.code(new iE.KeywordCxt(i,vS.default,"additionalProperties"));let s=(0,SS.allSchemaProperties)(r);for(let m of s)i.definedProperties.add(m);i.opts.unevaluated&&s.length&&i.props!==!0&&(i.props=Ol.mergeEvaluated.props(t,(0,Ol.toHash)(s),i.props));let c=s.filter(m=>!(0,Ol.alwaysValidSchema)(i,r[m]));if(c.length===0)return;let d=t.name("valid");for(let m of c)p(m)?l(m):(t.if((0,SS.propertyInData)(t,a,m,i.opts.ownProperties)),l(m),i.allErrors||t.else().var(d,!0),t.endIf()),e.it.definedProperties.add(m),e.ok(d);function p(m){return i.opts.useDefaults&&!i.compositeRule&&r[m].default!==void 0}o(p,"hasDefault");function l(m){e.subschema({keyword:"properties",schemaProp:m,dataProp:m},d)}o(l,"applyPropertySchema")}};$l.default=sE});var CS=k(zl=>{"use strict";Object.defineProperty(zl,"__esModule",{value:!0});var wS=pt(),ys=F(),bS=te(),RS=te(),cE={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,wS.allSchemaProperties)(r),d=c.filter(S=>(0,bS.alwaysValidSchema)(i,r[S]));if(c.length===0||d.length===c.length&&(!i.opts.unevaluated||i.props===!0))return;let p=s.strictSchema&&!s.allowMatchingProperties&&a.properties,l=t.name("valid");i.props!==!0&&!(i.props instanceof ys.Name)&&(i.props=(0,RS.evaluatedPropsToName)(t,i.props));let{props:m}=i;h();function h(){for(let S of c)p&&y(S),i.allErrors?v(S):(t.var(l,!0),v(S),t.if(l))}o(h,"validatePatternProperties");function y(S){for(let _ in p)new RegExp(S).test(_)&&(0,bS.checkStrictMode)(i,`property ${_} matches pattern ${S} (use allowMatchingProperties)`)}o(y,"checkMatchingProperties");function v(S){t.forIn("key",n,_=>{t.if((0,ys._)`${(0,wS.usePattern)(e,S)}.test(${_})`,()=>{let w=d.includes(S);w||e.subschema({keyword:"patternProperties",schemaProp:S,dataProp:_,dataPropType:RS.Type.Str},l),i.opts.unevaluated&&m!==!0?t.assign((0,ys._)`${m}[${_}]`,!0):!w&&!i.allErrors&&t.if((0,ys.not)(l),()=>t.break())})})}o(v,"validateProperties")}};zl.default=cE});var IS=k(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});var uE=te(),dE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,uE.alwaysValidSchema)(n,r)){e.fail();return}let a=t.name("valid");e.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:"must NOT be valid"}};Ml.default=dE});var PS=k(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var lE=pt(),pE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:lE.validateUnion,error:{message:"must match a schema in anyOf"}};ql.default=pE});var xS=k(Nl=>{"use strict";Object.defineProperty(Nl,"__esModule",{value:!0});var Ss=F(),mE=te(),fE={message:"must match exactly one schema in oneOf",params:o(({params:e})=>(0,Ss._)`{passingSchemas: ${e.passing}}`,"params")},hE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:fE,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,mE.alwaysValidSchema)(a,l)?t.var(d,!0):h=e.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},d),m>0&&t.if((0,Ss._)`${d} && ${s}`).assign(s,!1).assign(c,(0,Ss._)`[${c}, ${m}]`).else(),t.if(d,()=>{t.assign(s,!0),t.assign(c,m),h&&e.mergeEvaluated(h,Ss.Name)})})}o(p,"validateOneOf")}};Nl.default=hE});var kS=k(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var gE=te(),yE={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)})}};Dl.default=yE});var ES=k(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var vs=F(),AS=te(),SE={message:o(({params:e})=>(0,vs.str)`must match "${e.ifClause}" schema`,"message"),params:o(({params:e})=>(0,vs._)`{failingKeyword: ${e.ifClause}}`,"params")},vE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:SE,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,AS.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let a=TS(n,"then"),i=TS(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,vs.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,vs._)`${l}`):e.setParams({ifClause:l})}}o(p,"validateClause")}};function TS(e,t){let r=e.schema[t];return r!==void 0&&!(0,AS.alwaysValidSchema)(e,r)}o(TS,"hasSchema");jl.default=vE});var US=k(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var _E=te(),wE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,_E.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Hl.default=wE});var OS=k(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});var bE=Cl(),RE=uS(),CE=Il(),IE=lS(),PE=pS(),xE=hS(),kE=yS(),TE=Ul(),AE=_S(),EE=CS(),UE=IS(),OE=PS(),$E=xS(),zE=kS(),ME=ES(),qE=US();function NE(e=!1){let t=[UE.default,OE.default,$E.default,zE.default,ME.default,qE.default,kE.default,TE.default,xE.default,AE.default,EE.default];return e?t.push(RE.default,IE.default):t.push(bE.default,CE.default),t.push(PE.default),t}o(NE,"getApplicator");Ll.default=NE});var $S=k(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var Re=F(),DE={message:o(({schemaCode:e})=>(0,Re.str)`must match format "${e}"`,"message"),params:o(({schemaCode:e})=>(0,Re._)`{format: ${e}}`,"params")},jE={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:DE,code(e,t){let{gen:r,data:n,$data:a,schema:i,schemaCode:s,it:c}=e,{opts:d,errSchemaPath:p,schemaEnv:l,self:m}=c;if(!d.validateFormats)return;a?h():y();function h(){let v=r.scopeValue("formats",{ref:m.formats,code:d.code.formats}),S=r.const("fDef",(0,Re._)`${v}[${s}]`),_=r.let("fType"),w=r.let("format");r.if((0,Re._)`typeof ${S} == "object" && !(${S} instanceof RegExp)`,()=>r.assign(_,(0,Re._)`${S}.type || "string"`).assign(w,(0,Re._)`${S}.validate`),()=>r.assign(_,(0,Re._)`"string"`).assign(w,S)),e.fail$data((0,Re.or)(b(),R()));function b(){return d.strictSchema===!1?Re.nil:(0,Re._)`${s} && !${w}`}o(b,"unknownFmt");function R(){let z=l.$async?(0,Re._)`(${S}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,Re._)`${w}(${n})`,M=(0,Re._)`(typeof ${w} == "function" ? ${z} : ${w}.test(${n}))`;return(0,Re._)`${w} && ${w} !== true && ${_} === ${t} && !${M}`}o(R,"invalidFmt")}o(h,"validate$DataFormat");function y(){let v=m.formats[i];if(!v){b();return}if(v===!0)return;let[S,_,w]=R(v);S===t&&e.pass(z());function b(){if(d.strictSchema===!1){m.logger.warn(M());return}throw new Error(M());function M(){return`unknown format "${i}" ignored in schema at path "${p}"`}}o(b,"unknownFormat");function R(M){let Me=M instanceof RegExp?(0,Re.regexpCode)(M):d.code.formats?(0,Re._)`${d.code.formats}${(0,Re.getProperty)(i)}`:void 0,at=r.scopeValue("formats",{key:i,ref:M,code:Me});return typeof M=="object"&&!(M instanceof RegExp)?[M.type||"string",M.validate,(0,Re._)`${at}.validate`]:["string",M,at]}o(R,"getFormat");function z(){if(typeof v=="object"&&!(v instanceof RegExp)&&v.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Re._)`await ${w}(${n})`}return typeof _=="function"?(0,Re._)`${w}(${n})`:(0,Re._)`${w}.test(${n})`}o(z,"validCondition")}o(y,"validateFormat")}};Bl.default=jE});var zS=k(Gl=>{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});var HE=$S(),LE=[HE.default];Gl.default=LE});var MS=k(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.contentVocabulary=Qn.metadataVocabulary=void 0;Qn.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Qn.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var NS=k(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});var BE=Vy(),GE=aS(),VE=OS(),FE=zS(),qS=MS(),ZE=[BE.default,GE.default,(0,VE.default)(),FE.default,qS.metadataVocabulary,qS.contentVocabulary];Vl.default=ZE});var jS=k(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});_s.DiscrError=void 0;var DS;(function(e){e.Tag="tag",e.Mapping="mapping"})(DS||(_s.DiscrError=DS={}))});var LS=k(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var Xn=F(),Fl=jS(),HS=ts(),KE=ga(),JE=te(),WE={message:o(({params:{discrError:e,tagName:t}})=>e===Fl.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,"message"),params:o(({params:{discrError:e,tag:t,tagName:r}})=>(0,Xn._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`,"params")},YE={keyword:"discriminator",type:"object",schemaType:"object",error:WE,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,Xn._)`${r}${(0,Xn.getProperty)(c)}`);t.if((0,Xn._)`typeof ${p} == "string"`,()=>l(),()=>e.error(!1,{discrError:Fl.DiscrError.Tag,tag:p,tagName:c})),e.ok(d);function l(){let y=h();t.if(!1);for(let v in y)t.elseIf((0,Xn._)`${p} === ${v}`),t.assign(d,m(y[v]));t.else(),e.error(!1,{discrError:Fl.DiscrError.Mapping,tag:p,tagName:c}),t.endIf()}o(l,"validateMapping");function m(y){let v=t.name("valid"),S=e.subschema({keyword:"oneOf",schemaProp:y},v);return e.mergeEvaluated(S,Xn.Name),v}o(m,"applyTagSchema");function h(){var y;let v={},S=w(a),_=!0;for(let z=0;z<s.length;z++){let M=s[z];if(M?.$ref&&!(0,JE.schemaHasRulesButRef)(M,i.self.RULES)){let at=M.$ref;if(M=HS.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,at),M instanceof HS.SchemaEnv&&(M=M.schema),M===void 0)throw new KE.default(i.opts.uriResolver,i.baseId,at)}let Me=(y=M?.properties)===null||y===void 0?void 0:y[c];if(typeof Me!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);_=_&&(S||w(M)),b(Me,z)}if(!_)throw new Error(`discriminator: "${c}" must be required`);return v;function w({required:z}){return Array.isArray(z)&&z.includes(c)}function b(z,M){if(z.const)R(z.const,M);else if(z.enum)for(let Me of z.enum)R(Me,M);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function R(z,M){if(typeof z!="string"||z in v)throw new Error(`discriminator: "${c}" values must be unique strings`);v[z]=M}}o(h,"getMapping")}};Zl.default=YE});var BS=k((EF,QE)=>{QE.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Jl=k((me,Kl)=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.MissingRefError=me.ValidationError=me.CodeGen=me.Name=me.nil=me.stringify=me.str=me._=me.KeywordCxt=me.Ajv=void 0;var XE=Dy(),eU=NS(),tU=LS(),GS=BS(),rU=["/properties"],ws="http://json-schema.org/draft-07/schema",eo=class extends XE.default{static{o(this,"Ajv")}_addVocabularies(){super._addVocabularies(),eU.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(tU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(GS,rU):GS;this.addMetaSchema(t,ws,!1),this.refs["http://json-schema.org/schema"]=ws}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(ws)?ws:void 0)}};me.Ajv=eo;Kl.exports=me=eo;Kl.exports.Ajv=eo;Object.defineProperty(me,"__esModule",{value:!0});me.default=eo;var nU=ha();Object.defineProperty(me,"KeywordCxt",{enumerable:!0,get:o(function(){return nU.KeywordCxt},"get")});var to=F();Object.defineProperty(me,"_",{enumerable:!0,get:o(function(){return to._},"get")});Object.defineProperty(me,"str",{enumerable:!0,get:o(function(){return to.str},"get")});Object.defineProperty(me,"stringify",{enumerable:!0,get:o(function(){return to.stringify},"get")});Object.defineProperty(me,"nil",{enumerable:!0,get:o(function(){return to.nil},"get")});Object.defineProperty(me,"Name",{enumerable:!0,get:o(function(){return to.Name},"get")});Object.defineProperty(me,"CodeGen",{enumerable:!0,get:o(function(){return to.CodeGen},"get")});var oU=Xi();Object.defineProperty(me,"ValidationError",{enumerable:!0,get:o(function(){return oU.default},"get")});var aU=ga();Object.defineProperty(me,"MissingRefError",{enumerable:!0,get:o(function(){return aU.default},"get")})});var QS=k(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.formatNames=Ot.fastFormats=Ot.fullFormats=void 0;function Ut(e,t){return{validate:e,compare:t}}o(Ut,"fmtDef");Ot.fullFormats={date:Ut(KS,Xl),time:Ut(Yl(!0),ep),"date-time":Ut(VS(!0),WS),"iso-time":Ut(Yl(),JS),"iso-date-time":Ut(VS(),YS),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:lU,"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:SU,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:pU,int32:{type:"number",validate:hU},int64:{type:"number",validate:gU},float:{type:"number",validate:ZS},double:{type:"number",validate:ZS},password:!0,binary:!0};Ot.fastFormats={...Ot.fullFormats,date:Ut(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Xl),time:Ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ep),"date-time":Ut(/^\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,WS),"iso-time":Ut(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,JS),"iso-date-time":Ut(/^\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,YS),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};Ot.formatNames=Object.keys(Ot.fullFormats);function iU(e){return e%4===0&&(e%100!==0||e%400===0)}o(iU,"isLeapYear");var sU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,cU=[0,31,28,31,30,31,30,31,31,30,31,30,31];function KS(e){let t=sU.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&&iU(r)?29:cU[n])}o(KS,"date");function Xl(e,t){if(e&&t)return e>t?1:e<t?-1:0}o(Xl,"compareDate");var Wl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Yl(e){return o(function(r){let n=Wl.exec(r);if(!n)return!1;let a=+n[1],i=+n[2],s=+n[3],c=n[4],d=n[5]==="-"?-1:1,p=+(n[6]||0),l=+(n[7]||0);if(p>23||l>59||e&&!c)return!1;if(a<=23&&i<=59&&s<60)return!0;let m=i-l*d,h=a-p*d-(m<0?1:0);return(h===23||h===-1)&&(m===59||m===-1)&&s<61},"time")}o(Yl,"getTime");function ep(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}o(ep,"compareTime");function JS(e,t){if(!(e&&t))return;let r=Wl.exec(e),n=Wl.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e<t?-1:0}o(JS,"compareIsoTime");var Ql=/t|\s/i;function VS(e){let t=Yl(e);return o(function(n){let a=n.split(Ql);return a.length===2&&KS(a[0])&&t(a[1])},"date_time")}o(VS,"getDateTime");function WS(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}o(WS,"compareDateTime");function YS(e,t){if(!(e&&t))return;let[r,n]=e.split(Ql),[a,i]=t.split(Ql),s=Xl(r,a);if(s!==void 0)return s||ep(n,i)}o(YS,"compareIsoDateTime");var uU=/\/|:/,dU=/^(?:[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 lU(e){return uU.test(e)&&dU.test(e)}o(lU,"uri");var FS=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function pU(e){return FS.lastIndex=0,FS.test(e)}o(pU,"byte");var mU=-(2**31),fU=2**31-1;function hU(e){return Number.isInteger(e)&&e<=fU&&e>=mU}o(hU,"validateInt32");function gU(e){return Number.isInteger(e)}o(gU,"validateInt64");function ZS(){return!0}o(ZS,"validateNumber");var yU=/[^\\]\\Z/;function SU(e){if(yU.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}o(SU,"regex")});var XS=k(ro=>{"use strict";Object.defineProperty(ro,"__esModule",{value:!0});ro.formatLimitDefinition=void 0;var vU=Jl(),bt=F(),Ir=bt.operators,bs={formatMaximum:{okStr:"<=",ok:Ir.LTE,fail:Ir.GT},formatMinimum:{okStr:">=",ok:Ir.GTE,fail:Ir.LT},formatExclusiveMaximum:{okStr:"<",ok:Ir.LT,fail:Ir.GTE},formatExclusiveMinimum:{okStr:">",ok:Ir.GT,fail:Ir.LTE}},_U={message:o(({keyword:e,schemaCode:t})=>(0,bt.str)`should be ${bs[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,bt._)`{comparison: ${bs[e].okStr}, limit: ${t}}`,"params")};ro.formatLimitDefinition={keyword:Object.keys(bs),type:"string",schemaType:"string",$data:!0,error:_U,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 vU.KeywordCxt(i,c.RULES.all.format.definition,"format");d.$data?p():l();function p(){let h=t.scopeValue("formats",{ref:c.formats,code:s.code.formats}),y=t.const("fmt",(0,bt._)`${h}[${d.schemaCode}]`);e.fail$data((0,bt.or)((0,bt._)`typeof ${y} != "object"`,(0,bt._)`${y} instanceof RegExp`,(0,bt._)`typeof ${y}.compare != "function"`,m(y)))}o(p,"validate$DataFormat");function l(){let h=d.schema,y=c.formats[h];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${a}": format "${h}" does not define "compare" function`);let v=t.scopeValue("formats",{key:h,ref:y,code:s.code.formats?(0,bt._)`${s.code.formats}${(0,bt.getProperty)(h)}`:void 0});e.fail$data(m(v))}o(l,"validateFormat");function m(h){return(0,bt._)`${h}.compare(${r}, ${n}) ${bs[a].fail} 0`}o(m,"compareCode")},dependencies:["format"]};var wU=o(e=>(e.addKeyword(ro.formatLimitDefinition),e),"formatLimitPlugin");ro.default=wU});var nv=k((Aa,rv)=>{"use strict";Object.defineProperty(Aa,"__esModule",{value:!0});var no=QS(),bU=XS(),tp=F(),ev=new tp.Name("fullFormats"),RU=new tp.Name("fastFormats"),rp=o((e,t={keywords:!0})=>{if(Array.isArray(t))return tv(e,t,no.fullFormats,ev),e;let[r,n]=t.mode==="fast"?[no.fastFormats,RU]:[no.fullFormats,ev],a=t.formats||no.formatNames;return tv(e,a,r,n),t.keywords&&(0,bU.default)(e),e},"formatsPlugin");rp.get=(e,t="full")=>{let n=(t==="fast"?no.fastFormats:no.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function tv(e,t,r,n){var a,i;(a=(i=e.opts.code).formats)!==null&&a!==void 0||(i.formats=(0,tp._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}o(tv,"addFormats");rv.exports=Aa=rp;Object.defineProperty(Aa,"__esModule",{value:!0});Aa.default=rp});var _n={runtime:{invalid_request:{code:"invalid_request",seam:"runtime",status:400,title:"Bad Request",publicDetail:"The request did not match the route contract.",oauthError:"invalid_request"},forbidden:{code:"forbidden",seam:"runtime",status:403,title:"Forbidden",publicDetail:"The request is not allowed.",oauthError:"invalid_request"},not_found:{code:"not_found",seam:"runtime",status:404,title:"Not Found",publicDetail:"The requested resource was not found.",oauthError:"invalid_request"},internal_server_error:{code:"internal_server_error",seam:"runtime",status:500,title:"Internal Server Error",publicDetail:"The gateway failed to process the request.",oauthError:"server_error"}},config:{virtual_server_not_enabled:{code:"virtual_server_not_enabled",seam:"config",status:404,title:"Not Found",publicDetail:"The requested virtual server is not enabled."},unknown_upstream_server:{code:"unknown_upstream_server",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested upstream server is not configured.",oauthError:"invalid_request"},unknown_virtual_server:{code:"unknown_virtual_server",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested virtual server is not configured.",oauthError:"invalid_target"},unknown_auth_profile:{code:"unknown_auth_profile",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested upstream auth profile is not configured.",oauthError:"invalid_request"},virtual_server_upstream_mismatch:{code:"virtual_server_upstream_mismatch",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested virtual server does not belong to the selected upstream server.",oauthError:"invalid_request"}},downstream_auth:{authentication_required:{code:"authentication_required",seam:"downstream_auth",status:401,title:"Unauthorized",publicDetail:"Authentication is required to access this route.",oauthError:"invalid_client"},identity_context_missing:{code:"identity_context_missing",seam:"downstream_auth",status:403,title:"Forbidden",publicDetail:"Authenticated requests must include a gateway principal subject.",oauthError:"invalid_request"}},downstream_oauth:{browser_login_verification_failed:{code:"browser_login_verification_failed",seam:"downstream_oauth",status:400,title:"Connection failed",publicDetail:"The gateway could not verify the browser login response. Retry the login flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_auth:{provider_access_denied:{code:"provider_access_denied",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream authorization request was denied. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_invalid:{code:"oauth_state_invalid",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream connection request could not be verified. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_expired:{code:"oauth_state_expired",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream connection request expired. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_reused:{code:"oauth_state_reused",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"This upstream connection request was already used. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_callback_mismatch:{code:"oauth_callback_mismatch",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream callback did not match the initiating connection request.",callbackFailure:!0,oauthError:"invalid_request"},upstream_token_exchange_failed:{code:"upstream_token_exchange_failed",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The gateway could not complete the upstream token exchange. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"},upstream_client_registration_required:{code:"upstream_client_registration_required",seam:"upstream_auth",status:400,title:"Upstream OAuth client registration required",publicDetail:"The upstream authorization server supports neither gateway-hosted Client ID Metadata Documents nor Dynamic Client Registration. Register an upstream OAuth client manually before retrying.",oauthError:"invalid_request"},upstream_token_response_invalid:{code:"upstream_token_response_invalid",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream token response was invalid. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_mcp:{upstream_capability_invocation_failed:{code:"upstream_capability_invocation_failed",seam:"upstream_mcp",status:502,title:"Bad Gateway",publicDetail:"The upstream capability invocation failed. Retry later or reconnect the upstream if the issue persists."},upstream_import_failed:{code:"upstream_import_failed",seam:"upstream_mcp",status:502,title:"Bad Gateway",publicDetail:"The upstream capability import failed. Retry later or reconnect the upstream if the issue persists."}}},om={..._n.runtime,..._n.config,..._n.downstream_auth,..._n.downstream_oauth,..._n.upstream_auth,..._n.upstream_mcp};function _o(e){return typeof e=="string"&&Object.hasOwn(om,e)}o(_o,"isGatewayProblemCode");function Va(e){return _o(e)&&Ke(e).callbackFailure===!0}o(Va,"isGatewayCallbackFailureCode");function Ke(e){return om[e]}o(Ke,"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";default:return"internal_server_error"}}o(am,"readDefaultGatewayProblemCodeForStatus");var im="gatewayCode";function sm(e){let t=Ke(e);return{title:t.title,body:t.publicDetail}}o(sm,"readGatewayCallbackFailureContent");function ge(e){if(!(e instanceof Sn))return;let t=e.extensionMembers?.[im];return _o(t)?t:void 0}o(ge,"readGatewayProblemCode");function g(e,t,r){let n=typeof e=="string"?{code:e,...t===void 0?{}:{publicDetail:t,privateDetail:t},...r===void 0?{}:{cause:r}}:e,a=Ke(n.code),i=n.privateDetail??(Fa(n.code)?n.publicDetail??a.publicDetail:a.publicDetail),s=xw(n);return new Sn({message:i,extensionMembers:{[im]:n.code}},s===void 0?void 0:{cause:s})}o(g,"createGatewayRuntimeError");async function it(e,t,r){let n=Ke(r.code),a=kw(r.code,r.detail),i=Fa(r.code)?r.title??n.title:n.title,c={problem:{...vo.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),vo.format(c,e,t)}o(it,"gatewayProblemResponse");function Fa(e){return Ke(e).status<500}o(Fa,"canExposeGatewayProblemDetail");function xw(e){return!e.privateDetail||Fa(e.code)?e.cause:e.cause===void 0?new Error(e.privateDetail):new Error(e.privateDetail,{cause:e.cause})}o(xw,"readRuntimeErrorCause");function kw(e,t){let r=Ke(e);return Fa(e)&&t||r.publicDetail}o(kw,"readSafeGatewayProblemDetail");ae();ae();ae();var Tw=new Set(["localhost","::1"]);function Nt(e){return e.replace(/^\[(.*)\]$/,"$1").replace(/\.+$/,"").toLowerCase()}o(Nt,"normalizeHostname");function qe(e){let t=Nt(e.hostname);return e.protocol==="http:"&&(Tw.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}o(qe,"isLoopbackHttpUrl");var cm=new Ct("gateway-route");function um(e,t){cm.set(e,t)}o(um,"setGatewayRouteContext");function wo(e){return cm.get(e)}o(wo,"readGatewayRouteContext");function wn(e){let t=wo(e);if(!t)throw g("internal_server_error","Gateway route context has not been set");return t}o(wn,"requireGatewayRouteContext");var dm=new Ct("mcp-oauth-runtime-config");function bn(e,t){dm.set(e,t)}o(bn,"setMcpOAuthRuntimeConfig");function lm(e){let t=dm.get(e);if(!t)throw g("internal_server_error","MCP gateway OAuth config has not been set on the request context. An `mcp-oauth-inbound` policy (or `mcp-auth0-oauth-inbound`) must run before this handler, or the internal OAuth route wrapper must have populated the context.");return t}o(lm,"requireMcpOAuthRuntimeConfig");var bo=u.string().trim().min(1),Ro={accessTokenTtlSeconds:900,refreshTokenTtlSeconds:2592e3,cimdEnabled:!0},Aw=u.object({issuer:u.url(),jwksUrl:u.url(),audience:bo.optional()}),Ew=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(),Uw=u.object({accessTokenTtlSeconds:u.coerce.number().int().positive().default(Ro.accessTokenTtlSeconds),refreshTokenTtlSeconds:u.coerce.number().int().positive().default(Ro.refreshTokenTtlSeconds),cimdEnabled:u.boolean().default(Ro.cimdEnabled)}).strict().default(Ro),fc=u.object({oidc:Aw,browserLogin:Ew,gateway:Uw.optional().default(Ro)}).strict();function pm(e){return Ow(e.browserLogin.url)?"local_dev":"federated_oidc"}o(pm,"readBrowserLoginKind");function Ow(e){let t;try{t=new URL(e)}catch{return!1}return qe(t)&&t.pathname==="/oauth/dev-login"}o(Ow,"isLoopbackDevLoginUrl");function mm(e){return fc.parse(e)}o(mm,"parseMcpOAuthRuntimeConfig");function Pe(){let e;try{e=sc()}catch(t){throw g("internal_server_error","MCP gateway OAuth config can only be read during a request. Wrap tests in `runWithRequestContext` and ensure MCP OAuth routes are registered through `McpGatewayPlugin`.",t)}return lm(e)}o(Pe,"getGatewayOAuthConfig");ae();var $w=["shared-oauth","user-oauth","static-secret","user-secret","shared-secret"],zw=["none","client_secret_basic","client_secret_post"],Je=u.string().min(1).brand(),xe=u.string().min(1).brand(),We=u.string().min(1).brand(),ar=u.string().min(1).brand(),Za=u.enum($w),hc=u.enum(zw),Ka=u.string().trim().min(1).regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,"must be a valid HTTP header name"),gc=u.object({name:Ka,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict();ae();var W=u.string().datetime({offset:!0}).brand();function re(e){return W.parse(e.toISOString())}o(re,"toIsoTimestamp");function Dt(e,t){return new Date(e.getTime()+t*1e3)}o(Dt,"addSeconds");ae();function ie(e){return new URL(e).origin}o(ie,"readGatewayRequestOrigin");function ht(e){return ie(e)}o(ht,"readGatewayOAuthIssuer");function yc(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}o(yc,"truncate");function fm(e){return"cause"in e?e.cause:void 0}o(fm,"readCause");function Ye(e,t,r){if(!(r instanceof Error)){r!=null&&(e[`${t}Message`]=yc(String(r)));return}e[`${t}Name`]=r.name,e[`${t}Message`]=yc(r.message);let n=fm(r);for(let a=1;a<=4&&n instanceof Error;a+=1){let i=a===1?"cause":`cause${a}`;e[`${i}Name`]=n.name,e[`${i}Message`]=yc(n.message),n=fm(n)}}o(Ye,"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 hm(e,t){let r=Object.entries(t).filter(n=>n[1]!==void 0);r.length!==0&&e.log.setLogProperties?.(Object.fromEntries(r))}o(hm,"setLogProperties");function Sc(e,t){hm(e,{subjectId:t.subjectId})}o(Sc,"applyGatewayPrincipalLogProperties");function gm(e,t){hm(e,{upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId})}o(gm,"applyGatewayRouteLogProperties");ae();var Mw=43,qw=128,Nw=/^[A-Za-z0-9._~-]+$/,vc="S256",Ja=u.literal(vc),Wa=u.string().min(Mw).max(qw).regex(Nw);ae();var Ya=["none","client_secret_post","client_secret_basic"],Dw=[...Ya,"private_key_jwt"],jw=["awaiting_login","awaiting_setup"],Hw=u.string().min(1).brand(),Ne=u.string().min(1).brand(),Co=u.uuid().brand(),ct=u.uuid().brand(),Qa=u.uuid().brand(),_c=u.enum(Ya),Lw=u.enum(Dw),Zq=u.enum(jw),ym=u.object({client_id:Ne,client_name:u.string().min(1),redirect_uris:u.array(u.string().min(1)).min(1),token_endpoint_auth_method:Lw.default("none")}),wc=u.object({clientId:Ne,clientName:u.string().min(1),redirectUris:u.array(u.string().min(1)),tokenEndpointAuthMethod:_c,hashedClientSecret:u.string().optional(),clientSecretExpiresAt:W.optional(),clientExpiresAt:W,revokedAt:W.optional(),createdAt:W}),bc=u.object({clientId:Ne,resource:u.string(),virtualServerId:xe,subjectId:Hw,scope:u.string(),roles:u.array(u.string()),createdAt:W,expiresAt:W}),Kq=bc.extend({id:ct,redirectUri:u.string(),clientState:u.string().optional(),codeChallenge:u.string(),codeChallengeMethod:Ja}),Rc=bc.extend({id:Co,currentRefreshTokenHash:u.string().optional(),previousRefreshTokenHash:u.string().optional(),revokedAt:W.optional(),revokedReason:u.string().optional()}),Xa=bc.extend({tokenHash:u.string(),grantId:Co,revokedAt:W.optional()});function Cc(){return ct.parse(crypto.randomUUID())}o(Cc,"createDownstreamAuthorizationTransactionId");function Ic(){return Qa.parse(crypto.randomUUID())}o(Ic,"createDownstreamBrowserLoginStateId");function Sm(){return Co.parse(crypto.randomUUID())}o(Sm,"createDownstreamGrantId");var ye="mcp:tools";function vm(e,t){if(e===t)return!0;let r=new URL(e),n=new URL(t);return qe(r)&&qe(n)&&r.pathname===n.pathname&&r.search===n.search}o(vm,"redirectUriMatchesRegistration");function _m(e){return qe(e)&&e.pathname==="/oauth/dev-login"}o(_m,"isLoopbackDevLoginUrl");function ei(e,t){return new URL(e,ht(t)).toString()}o(ei,"buildGatewayOAuthUrl");function Pc(e){return new URL(`/mcp/${encodeURIComponent(e.virtualServerId)}`,ie(e.requestUrl)).toString()}o(Pc,"buildScopedAuthorizationServerIssuer");function Bw(e){return new URL(`/oauth/authorize/mcp/${encodeURIComponent(e.virtualServerId)}`,ie(e.requestUrl)).toString()}o(Bw,"buildScopedAuthorizationEndpoint");function xc(e){let t=Pe();return{issuer:ht(e),authorization_endpoint:ei("/oauth/authorize",e),token_endpoint:ei("/oauth/token",e),registration_endpoint:ei("/oauth/register",e),revocation_endpoint:ei("/oauth/revoke",e),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:[ye],code_challenge_methods_supported:[vc],token_endpoint_auth_methods_supported:Ya,revocation_endpoint_auth_methods_supported:["client_secret_basic","client_secret_post","none"],client_id_metadata_document_supported:t.gateway.cimdEnabled,"x-zuplo-browser-login-kind":pm(t)}}o(xc,"buildAuthorizationServerMetadata");function wm(e){let t=Pc(e);return{...xc(e.requestUrl),issuer:t,authorization_endpoint:Bw(e)}}o(wm,"buildScopedAuthorizationServerMetadata");var $r="2025-06-18";async function bm(e,t){try{let r=xe.parse(e.params.virtualServerId),n=Mr(r);return Response.json(Gw(n.virtualServerId,e.url))}catch(r){let n=ge(r);return it(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(bm,"protectedResourceMetadataHandler");function Gw(e,t){return{resource:zr(e,t),resource_name:e,authorization_servers:[Pc({virtualServerId:e,requestUrl:t})],bearer_methods_supported:["header"],scopes_supported:[ye],mcp_protocol_version:$r}}o(Gw,"buildProtectedResourceMetadataResponseBody");function zr(e,t){return new URL(`/mcp/${encodeURIComponent(e)}`,ie(t)).toString()}o(zr,"buildCanonicalMcpResourceForVirtualServer");function Rm(e,t){return new URL(`/.well-known/oauth-protected-resource/mcp/${encodeURIComponent(e)}`,ie(t)).toString()}o(Rm,"buildProtectedResourceMetadataUrlForVirtualServer");var Vw=u.record(u.string(),u.unknown()),Cm=u.string().min(1),Fw=u.union([Cm.transform(e=>[e]),u.array(Cm)]),ve=u.string().min(1).brand(),Zw=["zuploSubjectId","zuplo_subject_id","gatewaySubjectId","gateway_subject_id","subjectId","subject_id","https://zuplo.com/subject_id"],Kw=["https://zuplo.com/roles","roles","role","permissions","groups"],Im=new Ct("gateway-principal");function Jw(e){let t=Vw.safeParse(e);return t.success?t.data:{}}o(Jw,"toClaimRecord");function Ww(e){return e.issues[0]?.message??"Gateway principal is invalid"}o(Ww,"readValidationFailureDetail");function Yw(e,t,r){for(let i of Zw){let s=ve.safeParse(t[i]);if(s.success)return s.data}let n=ve.safeParse(e?.sub);if(!n.success)throw g("identity_context_missing",Ww(n.error));let a=typeof t.iss=="string"?t.iss:void 0;return!a||a===ht(r)?n.data:ve.parse(`${a}|${n.data}`)}o(Yw,"readNormalizedSubjectId");function Qw(e){let t=new Set;for(let r of Kw){let n=Fw.safeParse(e[r]);if(n.success)for(let a of n.data)t.add(a)}return t.size>0?[...t]:void 0}o(Qw,"readRoles");function Rn(e,t){let r=Jw(e?.data),n={subjectId:Yw(e,r,t)},a=Qw(r);return a&&(n.roles=a),n}o(Rn,"parseGatewayPrincipal");function Pm(e){let t=Tc(e);if(!t)throw g("identity_context_missing","Gateway principal has not been hydrated");return t}o(Pm,"requireGatewayPrincipal");function xm(e,t){Im.set(e,t)}o(xm,"setGatewayPrincipal");function Tc(e){return Im.get(e)}o(Tc,"readGatewayPrincipal");function ti(e){let r=['realm="OAuth"',`resource_metadata="${kc(Rm(e.virtualServerId,e.requestUrl))}"`];return e.error!==void 0&&r.push(`error="${e.error}"`),e.errorDescription!==void 0&&r.push(`error_description="${kc(e.errorDescription)}"`),e.scope!==void 0&&r.push(`scope="${kc(e.scope)}"`),`Bearer ${r.join(", ")}`}o(ti,"buildGatewayBearerChallenge");function kc(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(kc,"sanitizeQuotedHeaderParameter");ae();ae();function ri(e){if(e===void 0||e.length===0)return;if(!e.startsWith("/")||e.startsWith("//"))throw g("invalid_request","returnTo must be a same-origin relative path.");let t=new URL(e,"https://gateway.local");if(t.origin!=="https://gateway.local"||t.username||t.password||t.hash||t.pathname.startsWith("//"))throw g("invalid_request","returnTo must be a same-origin relative path without credentials or fragments.");return`${t.pathname}${t.search}`}o(ri,"parseSafeRelativeReturnTo");ae();var Xw=["user","shared"],Cn=u.enum(Xw);function ir(e){return{mode:"user",subjectId:e}}o(ir,"buildUserUpstreamConnectionOwner");function ni(){return{mode:"shared"}}o(ni,"buildSharedUpstreamConnectionOwner");var km=u.object({ownerMode:Cn,initiatedBySubjectId:ve,ownerSubjectId:ve.optional(),upstreamServerId:Je,authProfileId:We,virtualServerId:xe,returnTo:u.string().min(1).transform(e=>ri(e)).optional()});function Tm(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(Tm,"validateUpstreamOwnerState");var In=km.superRefine(Tm),Am=km.omit({returnTo:!0}).superRefine(Tm);function Io(e){return In.parse({ownerMode:e.owner.mode,initiatedBySubjectId:e.initiatedBySubjectId,ownerSubjectId:e.owner.mode==="user"?e.owner.subjectId:void 0,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,returnTo:e.returnTo})}o(Io,"buildUpstreamOwnerState");function Pn(e){if(e.ownerMode==="shared")return ni();if(!e.ownerSubjectId)throw g("oauth_state_invalid","User-owned upstream state is missing the owner subject.");return ir(e.ownerSubjectId)}o(Pn,"resolveUpstreamConnectionOwnerFromState");var eb=["active","not_connected","reconsent_required"],tb=["basic_auth_app_password","bearer_token"],Em=u.string().trim().min(1).brand(),xn=u.uuid().brand(),Po=u.uuid().brand(),Ac=u.enum(eb),rb=u.enum(tb),Um=u.object({encryptedClientInformation:u.string().optional(),encryptedDiscoveryState:u.string().optional(),connectedBySubjectId:ve.optional()}),nb=Um.extend({encryptedStaticSecret:u.string().optional(),staticSecretKind:rb.optional(),staticSecretLabel:u.string().min(1).optional(),staticSecretUsername:u.string().min(1).optional()}).strict(),ob=u.object({id:Em,subjectId:ve.optional(),ownerMode:Cn,upstreamServerId:Je,authProfileId:We,status:Ac,encryptedAccessToken:u.string().min(1).optional(),encryptedRefreshToken:u.string().min(1).optional(),scopes:u.array(u.string()),expiresAt:W.optional(),metadata:nb.optional(),createdAt:W,updatedAt:W});function Ec(e,t){e.ownerMode==="user"&&(e.subjectId||t.addIssue({code:u.ZodIssueCode.custom,message:"User-owned upstream connections require subjectId",path:["subjectId"]})),e.ownerMode==="shared"&&e.subjectId!==void 0&&t.addIssue({code:u.ZodIssueCode.custom,message:"Shared upstream connections must not include subjectId",path:["subjectId"]})}o(Ec,"validateUpstreamConnectionOwnerShape");var kn=ob.superRefine(Ec);function qr(e){return JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId])}o(qr,"readUpstreamConnectionLookupKey");var Uc=In.extend({id:xn,callbackPath:u.string().min(1),expiresAt:W,codeVerifier:u.string().optional(),redirectUri:u.url(),returnOrigin:u.url().optional()}).extend(Um.shape);function Om(e){let t=e?.status??"not_connected",r={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}o(Om,"readUpstreamConnectionStatus");function oi(){return Em.parse(`mcpgw2uc_${crypto.randomUUID()}`)}o(oi,"createUpstreamConnectionId");function $m(){return xn.parse(crypto.randomUUID())}o($m,"createOAuthStateId");function zm(){return Po.parse(crypto.randomUUID())}o(zm,"createBrowserConnectTicketId");ae();var $c=u.discriminatedUnion("mode",[u.object({mode:u.literal("user"),subjectId:ve}).strict(),u.object({mode:u.literal("shared")}).strict()]),qm=u.object({owner:$c,upstreamServerId:Je,authProfileId:We}).strict(),Nm=u.object({items:u.array(qm).min(1).max(100)}).strict(),zc=u.object({items:u.array(u.object({key:u.object({ownerMode:Cn,subjectId:ve.optional(),upstreamServerId:Je,authProfileId:We}).strict(),connection:kn.strict().optional()}).strict())}).strict(),Dm=kn.omit({createdAt:!0,updatedAt:!0}).strict().superRefine(Ec),jm=kn.strict(),Hm=u.object({owner:$c,upstreamServerId:Je,authProfileId:We}).strict(),Lm=u.object({owner:$c,upstreamServerId:Je,authProfileId:We,connection:kn.strict().optional(),connectionStatus:u.object({connected:u.boolean(),status:Ac,updatedAt:kn.shape.updatedAt.optional()}).strict()}).strict(),ab=u.enum(["none","client_secret_basic","client_secret_post"]),Nr=u.object({clientId:Ne,clientName:u.string().min(1),tokenEndpointAuthMethod:ab}).strict(),Mc=u.discriminatedUnion("method",[u.object({method:u.literal("none"),clientId:Ne}).strict(),u.object({method:u.enum(["client_secret_basic","client_secret_post"]),clientId:Ne,clientSecretHashInput:u.string().min(1)}).strict()]),qc=u.object({id:ct,currentStateHash:u.string().min(1),clientId:Ne,redirectUri:u.string().min(1),resource:u.string().min(1),virtualServerId:xe,clientState:u.string().optional(),scope:u.string(),codeChallenge:u.string().min(1),codeChallengeMethod:u.literal("S256"),createdAt:W,expiresAt:W,consumedAt:W.optional()}).strict(),Mm=qc.omit({id:!0,consumedAt:!0}).extend({transactionId:ct,client:Nr.optional()}).strict(),Nc=u.object({subjectId:ve,roles:u.array(u.string()).optional()}).strict(),ib=qc.extend({phase:u.literal("awaiting_login")}).strict(),Oc=qc.extend({phase:u.literal("awaiting_setup"),principal:Nc}).strict(),sb=u.discriminatedUnion("phase",[ib,Oc]),Dc=u.object({transaction:sb,client:Nr}).strict(),Bm=wc.omit({revokedAt:!0}).strict(),Gm=u.discriminatedUnion("kind",[u.object({kind:u.literal("registered"),client:Nr}).strict(),u.object({kind:u.literal("already_exists")}).strict()]),Vm=u.object({clientId:Ne}).strict(),Fm=u.discriminatedUnion("kind",[u.object({kind:u.literal("found"),client:wc.strict()}).strict(),u.object({kind:u.literal("missing")}).strict()]),Zm=u.discriminatedUnion("phase",[Mm.extend({phase:u.literal("awaiting_login")}).strict(),Mm.extend({phase:u.literal("awaiting_setup"),principal:Nc}).strict()]),Km=u.discriminatedUnion("kind",[Dc.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()]),Jm=u.object({transactionId:ct,currentStateHash:u.string().min(1),now:W}).strict(),Wm=u.discriminatedUnion("kind",[Dc.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()]),Ym=u.object({transactionId:ct,expectedPhase:u.literal("awaiting_login"),currentStateHash:u.string().min(1),nextStateHash:u.string().min(1),nextPhase:u.literal("awaiting_setup"),principal:Nc,now:W}).strict(),Qm=u.discriminatedUnion("kind",[Dc.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()]),Xm=u.discriminatedUnion("decision",[u.object({decision:u.literal("approve"),transactionId:ct,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:ve}).strict(),authorizationCodeHash:u.string().min(1),authorizationCodeExpiresAt:W,grantId:Co,now:W}).strict(),u.object({decision:u.literal("cancel"),transactionId:ct,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:ve}).strict(),now:W}).strict()]),ef=u.discriminatedUnion("kind",[u.object({kind:u.literal("approved"),transaction:Oc,client:Nr}).strict(),u.object({kind:u.literal("cancelled"),transaction:Oc,client:Nr}).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()]),tf=u.object({clientAuth:Mc,codeHash:u.string().min(1),redirectUri:u.string().min(1),resource:u.string().min(1).optional(),codeChallenge:u.string().min(1),currentRefreshTokenHash:u.string().min(1),accessTokenHash:u.string().min(1),grantExpiresAt:W,accessTokenExpiresAt:W,now:W}).strict(),rf=u.discriminatedUnion("kind",[u.object({kind:u.literal("exchanged"),client:Nr,grant:Rc.strict()}).strict(),u.object({kind:u.literal("invalid_client")}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("resource_mismatch")}).strict(),u.object({kind:u.literal("binding_mismatch")}).strict()]),nf=u.object({clientAuth:Mc,currentRefreshTokenHash:u.string().min(1),nextRefreshTokenHash:u.string().min(1),accessTokenHash:u.string().min(1),resource:u.string().min(1).optional(),accessTokenExpiresAt:W,now:W}).strict(),of=u.discriminatedUnion("kind",[u.object({kind:u.literal("rotated"),client:Nr,grant:Rc.strict(),accessToken:Xa.strict(),matched:u.literal("current")}).strict(),u.object({kind:u.literal("invalid_client")}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("resource_mismatch")}).strict(),u.object({kind:u.literal("revoked")}).strict()]),af=u.object({clientAuth:Mc,tokenHash:u.string().min(1),now:W}).strict(),sf=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()]),cf=u.object({tokenHash:u.string().min(1),now:W}).strict(),uf=u.discriminatedUnion("kind",[u.object({kind:u.literal("valid"),record:Xa.strict()}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("revoked")}).strict()]),df=u.object({accessTokenHash:u.string().min(1),resource:u.string().min(1),virtualServerId:xe,upstreamConnectionKeys:u.array(qm).max(100),now:W}).strict(),lf=u.discriminatedUnion("kind",[u.object({kind:u.literal("authorized"),principal:u.object({subjectId:ve,roles:u.array(u.string())}).strict(),accessToken:Xa.strict(),upstreamConnections:zc.shape.items}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("revoked")}).strict(),u.object({kind:u.literal("resource_mismatch")}).strict(),u.object({kind:u.literal("principal_mismatch")}).strict()]),pf=u.object({record:Uc}).strict(),mf=u.object({kind:u.literal("saved")}).strict(),ff=u.object({id:xn,now:W}).strict(),hf=u.discriminatedUnion("kind",[u.object({kind:u.literal("available"),record:Uc}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("missing")}).strict()]),gf=u.object({id:Po,expiresAt:W,now:W}).strict(),yf=u.discriminatedUnion("kind",[u.object({kind:u.literal("available")}).strict(),u.object({kind:u.literal("consumed")}).strict()]);var Sf=100,cb=new Set(["undefined","null","nan"]);function vf(e){return e!==null&&typeof e=="object"}o(vf,"isProblemDetailsShape");var ub="/zups/v2/mcp/storage";function ke(e){return`${ub}/${e}`}o(ke,"buildStoragePath");function db(){return ke("upstream-connections/batch-get")}o(db,"buildBatchGetUpstreamConnectionsPath");function lb(){return ke("upstream-connections/upsert")}o(lb,"buildUpsertUpstreamConnectionPath");function pb(){return ke("authorization/read-setup")}o(pb,"buildReadAuthorizationSetupPath");function mb(){return ke("oauth/register-client")}o(mb,"buildRegisterClientPath");function fb(){return ke("oauth/read-client")}o(fb,"buildReadClientPath");function hb(){return ke("authorization/start")}o(hb,"buildStartAuthorizationPath");function gb(){return ke("authorization/read-pending")}o(gb,"buildReadPendingAuthorizationPath");function yb(){return ke("authorization/advance-pending")}o(yb,"buildAdvancePendingAuthorizationPath");function Sb(){return ke("authorization/decide-setup")}o(Sb,"buildDecideAuthorizationSetupPath");function vb(){return ke("token/exchange-authorization-code")}o(vb,"buildExchangeAuthorizationCodePath");function _b(){return ke("token/refresh")}o(_b,"buildRefreshTokenPath");function wb(){return ke("token/revoke")}o(wb,"buildRevokeOAuthTokenPath");function bb(){return ke("token/validate-access-token")}o(bb,"buildValidateAccessTokenPath");function Rb(){return ke("mcp/authorize-and-load-connections")}o(Rb,"buildAuthorizeAndLoadConnectionsPath");function Cb(){return ke("upstream-oauth-state/save")}o(Cb,"buildSaveUpstreamOAuthStatePath");function Ib(){return ke("upstream-oauth-state/consume")}o(Ib,"buildConsumeUpstreamOAuthStatePath");function Pb(){return ke("browser-connect-ticket/consume")}o(Pb,"buildConsumeBrowserConnectTicketPath");function xb(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(xb,"responseKeyMatchesLookup");function kb(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(kb,"authorizationSetupMatchesLookup");function bf(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(bf,"connectionMatchesLookup");function Tb(e,t){return e.ownerMode===t.ownerMode&&(e.subjectId??"")===(t.subjectId??"")&&e.upstreamServerId===t.upstreamServerId&&e.authProfileId===t.authProfileId&&e.status===t.status&&(e.encryptedAccessToken??"")===(t.encryptedAccessToken??"")&&(e.encryptedRefreshToken??"")===(t.encryptedRefreshToken??"")&&Hc(e.scopes,t.scopes)&&jc(e.expiresAt,t.expiresAt)&&Eb(e.metadata,t.metadata)}o(Tb,"connectionMatchesUpsertRecord");function jc(e,t){return e===void 0||t===void 0?e===t:Date.parse(e)===Date.parse(t)}o(jc,"optionalTimestampInstantsMatch");function Ab(e,t){return Date.parse(e)<=Date.parse(t)}o(Ab,"timestampInstantIsAtOrBefore");function Hc(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}o(Hc,"stringArraysMatch");function Eb(e,t){let r=_f(e),n=_f(t),a=Object.fromEntries(n);return r.length===n.length&&r.every(([i,s])=>a[i]===s)}o(Eb,"metadataMatches");function _f(e){return Object.entries(e??{}).filter(t=>t[1]!==void 0)}o(_f,"definedMetadataEntries");function we(e,t){throw g({code:"internal_server_error",privateDetail:e,cause:t})}o(we,"throwInvalidStorageResponse");async function Ub(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(Ub,"parseRuntimeHttpStorageResponse");function Rf(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];xb(n.key,a)||we("Gateway Service storage response key did not match the request."),n.connection!==void 0&&!bf(n.connection,a)&&we("Gateway Service storage response connection did not match the response key.")}}o(Rf,"validateUpstreamConnectionItemsMatchLookups");function Ob(e,t){kb(e,t)||we("Gateway Service storage response authorization setup did not match the request."),e.connection!==void 0&&!bf(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(Ob,"validateAuthorizationSetupResponseMatchesLookup");function $b(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($b,"validateRegisterClientResponseMatchesRequest");function zb(e,t){e.kind==="found"&&e.client.clientId!==t.clientId&&we("Gateway Service storage response client did not match the request.")}o(zb,"validateReadClientResponseMatchesRequest");function Mb(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(Mb,"validateStartAuthorizationResponseMatchesRequest");function wf(e,t){e.kind!=="available"&&e.kind!=="advanced"||((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."))}o(wf,"validatePendingAuthorizationResponseMatchesRequest");function qb(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(qb,"validateAuthorizationSetupDecisionResponseMatchesRequest");function Nb(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(Nb,"validateExchangeAuthorizationCodeResponseMatchesRequest");function Db(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||!Ab(e.accessToken.expiresAt,t.accessTokenExpiresAt)||!Lb(e.accessToken,e.grant))&&we("Gateway Service storage response token refresh access token did not match the request."))}o(Db,"validateRefreshTokenResponseMatchesRequest");function jb(e,t){e.kind==="valid"&&e.record.tokenHash!==t.tokenHash&&we("Gateway Service storage response access token did not match the request.")}o(jb,"validateAccessTokenValidationResponseMatchesRequest");function Hb(e,t){e.kind==="authorized"&&((e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.resource!==t.resource||e.accessToken.virtualServerId!==t.virtualServerId||e.principal.subjectId!==e.accessToken.subjectId||!Hc(e.principal.roles,e.accessToken.roles))&&we("Gateway Service storage response MCP authorization did not match the request."),Rf(e.upstreamConnections,t.upstreamConnectionKeys))}o(Hb,"validateAuthorizeAndLoadConnectionsResponseMatchesRequest");function Lb(e,t){return e.clientId===t.clientId&&e.resource===t.resource&&e.virtualServerId===t.virtualServerId&&e.subjectId===t.subjectId&&e.scope===t.scope&&Hc(e.roles,t.roles)}o(Lb,"accessTokenMatchesGrant");async function Bb(e){try{return await e.clone().json()}catch{return}}o(Bb,"readProblemDetails");async function Gb(e){let t=await Bb(e),r=vf(t)&&typeof t.status=="number"?t.status:e.status,n=vf(t)&&_o(t.code)?t.code:am(r);throw g({code:n,privateDetail:`Gateway Service storage request failed with HTTP ${r}.`})}o(Gb,"throwRuntimeHttpStorageError");var ai=class{static{o(this,"RuntimeHttpStorageClient")}#t;#r;constructor(t){this.#t=t.baseUrl??So.instance.zuploEdgeApiUrl,this.#r=t.fetch??fetch}#n(t){let r;try{r=new URL(t,this.#t)}catch(n){throw g("internal_server_error",`Gateway Service storage base URL is not a valid URL. Got ${JSON.stringify(this.#t)}. Verify the gateway runtime configuration.`,n)}if(r.protocol!=="https:"&&r.protocol!=="http:")throw g("internal_server_error",`Gateway Service storage base URL must use http(s); got protocol "${r.protocol}" from ${JSON.stringify(this.#t)}.`);if(!r.hostname||cb.has(r.hostname))throw g("internal_server_error",`Gateway Service storage base URL has an invalid hostname "${r.hostname}" (parsed from ${JSON.stringify(this.#t)}). The configured value is likely coerced from an unset environment variable.`);return r}async#e(t){let r=t.requestSchema.parse(t.input),n=this.#n(t.path),a=new Headers({"Content-Type":"application/json"});Zp(a);let i=await this.#r(n,{method:"POST",headers:a,body:JSON.stringify(r)});return i.ok||await Gb(i),{request:r,response:await Ub(i,t.responseSchema)}}async batchGetUpstreamConnections(t){if(t.length===0)return[];let r=[],n=new Map,a=t.map(s=>{let c=qr(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+=Sf){let c=r.slice(s,s+Sf);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:lb(),requestSchema:Dm,responseSchema:jm});return Tb(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:pb(),requestSchema:Hm,responseSchema:Lm});return Ob(n,r),n}async registerClient(t){let{request:r,response:n}=await this.#e({input:t,path:mb(),requestSchema:Bm,responseSchema:Gm});return $b(n,r),n}async readClient(t){let{request:r,response:n}=await this.#e({input:t,path:fb(),requestSchema:Vm,responseSchema:Fm});return zb(n,r),n}async startAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:hb(),requestSchema:Zm,responseSchema:Km});return Mb(n,r),n}async readPendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:gb(),requestSchema:Jm,responseSchema:Wm});return wf(n,r),n}async advancePendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:yb(),requestSchema:Ym,responseSchema:Qm});return wf(n,r),n}async decideAuthorizationSetup(t){let{request:r,response:n}=await this.#e({input:t,path:Sb(),requestSchema:Xm,responseSchema:ef});return qb(n,r),n}async saveUpstreamOAuthState(t){let{response:r}=await this.#e({input:t,path:Cb(),requestSchema:pf,responseSchema:mf});return r}async consumeUpstreamOAuthState(t){let{request:r,response:n}=await this.#e({input:t,path:Ib(),requestSchema:ff,responseSchema:hf});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:Pb(),requestSchema:gf,responseSchema:yf});return r}async exchangeAuthorizationCode(t){let{request:r,response:n}=await this.#e({input:t,path:vb(),requestSchema:tf,responseSchema:rf});return Nb(n,r),n}async refreshToken(t){let{request:r,response:n}=await this.#e({input:t,path:_b(),requestSchema:nf,responseSchema:of});return Db(n,r),n}async revokeOAuthToken(t){let{response:r}=await this.#e({input:t,path:wb(),requestSchema:af,responseSchema:sf});return r}async validateAccessToken(t){let{request:r,response:n}=await this.#e({input:t,path:bb(),requestSchema:cf,responseSchema:uf});return jb(n,r),n}async authorizeAndLoadConnections(t){let{request:r,response:n}=await this.#e({input:t,path:Rb(),requestSchema:df,responseSchema:lf});return Hb(n,r),n}async#o(t){let r={items:[...t]},{response:n}=await this.#e({input:r,path:db(),requestSchema:Nm,responseSchema:zc});return Rf(n.items,t),n.items.map(a=>a.connection)}};var Vb="__zuploMcpGatewayStorageBackend",Lc;function Fb(){return new ai({})}o(Fb,"buildProductionStorageBackend");function K(){let e=globalThis[Vb];return e||(Lc||(Lc=Fb()),Lc)}o(K,"getStorage");function Zb(e,t){let r=Tc(e),n=wo(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 nm(e,{...t,subjectId:r?.subjectId,ownerMode:a,upstreamAuthMode:i,virtualServerName:s,upstreamServerName:c,upstreamServerTitle:d,authProfileId:p})}o(Zb,"buildMcpAnalyticsMetadata");function V(e,t){try{e.analyticsContext.addAnalyticsEvent(t.value??1,t.eventType,Zb(e,t),t.unit)}catch(r){e.log?.warn?.({event:"mcp_analytics_emit_failed",errorName:r instanceof Error?r.name:"unknown"})}}o(V,"emitMcpAnalyticsEvent");import{base64url as Bc}from"jose";var Kb="sha256:",Jb=32;function Cf(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Cf,"copyToArrayBuffer");function jt(){let e=crypto.getRandomValues(new Uint8Array(Jb));return Bc.encode(e)}o(jt,"createOpaqueToken");async function le(e){let t=await crypto.subtle.digest("SHA-256",Cf(new TextEncoder().encode(e)));return`${Kb}${Bc.encode(new Uint8Array(t))}`}o(le,"hashOpaqueValue");async function If(e){let t=await crypto.subtle.digest("SHA-256",Cf(new TextEncoder().encode(e)));return Bc.encode(new Uint8Array(t))}o(If,"calculatePkceS256Challenge");function Gc(e){let t=e.headers.get("authorization"),[r,n]=t?.split(/\s+/,2)??[];if(!(r?.toLowerCase()!=="bearer"||!n))return n}o(Gc,"readBearerToken");function Wb(e,t,r){return it(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":r}})}o(Wb,"gatewayAuthenticationRequiredResponse");function Yb(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(Yb,"tokenValidationReasonCode");async function Qb(e,t,r){let n=await K().validateAccessToken({tokenHash:await le(e),now:re(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=Yb(n.kind);throw V(t,{eventType:B.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:r,reasonClass:"auth",reasonCode:a,attributes:{validationKind:n.kind}}),V(t,{eventType:B.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r,httpStatusCode:401,reasonClass:"auth",reasonCode:a}),g("authentication_required","Gateway access token is expired, revoked, or invalid.")}return n.record}o(Qb,"validateGatewayAccessToken");function Xb(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"),V(t,{eventType:B.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:e.virtualServerId,reasonClass:"auth",reasonCode:"invalid_audience"}),V(t,{eventType:B.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:e.virtualServerId,httpStatusCode:401,reasonClass:"auth",reasonCode:"invalid_audience"}),g("authentication_required","Gateway access token was not issued for this MCP resource.")}o(Xb,"assertAccessTokenResource");function eR(e,t,r){return it(e,t,{code:"forbidden",detail:"Gateway access token is missing the required MCP scope.",headers:{"WWW-Authenticate":ti({virtualServerId:r,requestUrl:e.url,error:"insufficient_scope",errorDescription:`The access token is missing the ${ye} scope required by this MCP resource.`,scope:ye})}})}o(eR,"insufficientScopeResponse");function tR(e){return{subjectId:e.subjectId,roles:e.roles}}o(tR,"principalFromAccessToken");function rR(e){let t=ge(e.error),r={event:"gateway_access_token_rejected",code:t??"authentication_required",virtualServerId:e.virtualServerId};return e.error instanceof Error?(r.errorName=e.error.name,r.errorMessage=e.error.message):e.error!==void 0&&e.error!==null&&(r.errorMessage=String(e.error)),e.context.log.warn(r,"Gateway access token rejected; MCP request denied"),it(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":ti({virtualServerId:e.virtualServerId,requestUrl:e.request.url,error:"invalid_token",errorDescription:"The access token is expired, malformed, or invalid."})}})}o(rR,"gatewayTokenRejectedResponse");async function Vc(e,t){let r=wn(t),n=zr(r.virtualServerId,e.url),a=Gc(e),i=ti({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"),V(t,{eventType:B.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r.virtualServerId,httpStatusCode:401,reasonClass:"auth",reasonCode:"missing_token"}),Wb(e,t,i);try{let s=await Qb(a,t,r.virtualServerId);if(Xb({accessToken:s,resource:n,virtualServerId:r.virtualServerId},t),s.scope!==ye)return t.log.warn({event:"gateway_access_token_insufficient_scope",code:"forbidden",tokenScope:s.scope,requiredScope:ye,virtualServerId:r.virtualServerId,clientId:s.clientId},"Gateway access token does not have the required MCP scope"),V(t,{eventType:B.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:r.virtualServerId,reasonClass:"auth",reasonCode:"insufficient_scope",attributes:{tokenScope:s.scope,requiredScope:ye,clientId:s.clientId}}),V(t,{eventType:B.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r.virtualServerId,httpStatusCode:403,reasonClass:"auth",reasonCode:"insufficient_scope"}),eR(e,t,r.virtualServerId);let c=tR(s);return xm(t,c),Sc(t,c),V(t,{eventType:B.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED,outcome:"success",virtualServerName:r.virtualServerId,attributes:{clientId:s.clientId}}),e}catch(s){return rR({request:e,context:t,error:s,virtualServerId:r.virtualServerId})}}o(Vc,"gatewayTokenInbound");var Tn={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},nR="oauth-protected-resource-metadata",oR="/.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 iR(e){return e.hasGatewayRouteContext?Tn.VIRTUAL_MCP_SERVER:e.routeOperationId===nR||e.routeOperationId===void 0&&e.routePath.startsWith(oR)?Tn.OAUTH_PROTECTED_RESOURCE_METADATA:Tn.OTHER}o(iR,"classifyAnalyticsRouteSurface");function sR(e){let t=e.route.path;return{routePath:t,routeSurface:iR({routePath:t,routeOperationId:aR(e),hasGatewayRouteContext:wo(e)!==void 0})}}o(sR,"readAnalyticsRequestContext");function cR(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===Tn.VIRTUAL_MCP_SERVER}o(cR,"isIntentionalMethodRejection");function uR(e){return cR(e)||e.response.status===401&&e.routeSurface===Tn.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}o(uR,"classifyRequestCompletedOutcome");async function Fc(e,t){let r=Date.now(),n=sR(t);return V(t,{eventType:B.MCP_REQUEST_RECEIVED,outcome:"success",routeSurface:n.routeSurface,httpMethod:e.method}),cc.getContextExtensions(t).addHandlerResponseHook(a=>{let i=uR({response:a,routeSurface:n.routeSurface});V(t,{eventType:B.MCP_REQUEST_COMPLETED,outcome:i,routeSurface:n.routeSurface,httpStatusCode:a.status,httpMethod:e.method,latencyMs:Date.now()-r})}),e}o(Fc,"analyticsContextInbound");function dR(e){return e instanceof Response}o(dR,"isResponse");var Pf="/mcp/";function lR(e){let t=e.route.path;if(!t.startsWith(Pf))throw new ue(`Route ${t} is bound to mcp-oauth-inbound but does not match the /mcp/{virtualServerId} convention.`);let r=t.slice(Pf.length);if(!r||r.includes("/"))throw new ue(`Route ${t} is bound to mcp-oauth-inbound but must use exactly one /mcp/{virtualServerId} segment.`);return r}o(lR,"readVirtualServerIdFromRoute");async function xo(e,t){let n={virtualServerId:xe.parse(lR(t))};um(t,n),gm(t,n);let a=await Fc(e,t);return dR(a)?a:Vc(a,t)}o(xo,"mcpOAuthInboundPolicy");function ii(e,t,r){let n=e.safeParse(t);if(n.success)return n.data;throw new ue(`${r} is misconfigured. Validation failed:
|
|
33
|
-
${
|
|
34
|
-
`)}o(pR,"formatZodIssues");var mR=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.'}),fR=u.object({auth0Domain:mR,audience:u.string().trim().min(1).optional(),clientId:u.string({error:"clientId is required and must be a string"}).trim().min(1,"clientId is required (commonly set via $env(AUTH0_CLIENT_ID))"),clientSecret:u.string().trim().min(1).optional(),scope:u.string().trim().min(1).optional(),gateway:u.object({accessTokenTtlSeconds:u.number().int().positive().optional(),refreshTokenTtlSeconds:u.number().int().positive().optional(),cimdEnabled:u.boolean().optional()}).strict().optional(),browserLoginOverrides:u.object({remoteTimeoutMs:u.number().int().positive().optional(),stateTtlSeconds:u.number().int().positive().optional(),sessionTtlSeconds:u.number().int().positive().optional()}).strict().optional()}).strict(),Zc=class extends vn{static{o(this,"McpAuth0OAuthInboundPolicy")}#t;constructor(t,r){let n=xf(t,r);super(n,r),this.#t=Tf(n,r)}async handler(t,r){return Rt("policy.inbound.mcp-auth0-oauth"),bn(r,this.#t),xo(t,r)}};function xf(e,t){return ii(fR,e,`MCP Auth0 OAuth policy "${t}"`)}o(xf,"parseAuth0OAuthOptions");function kf(e,t="mcp-auth0-oauth-inbound"){let r=xf(e,t);return Tf(r,t)}o(kf,"auth0OptionsToMcpOAuthRuntimeConfig");function Tf(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 mm({oidc:{issuer:r,jwksUrl:n,...e.audience===void 0?{}:{audience:e.audience}},browserLogin:{url:a,tokenUrl:i,clientId:e.clientId,clientSecret:e.clientSecret,scope:e.scope??"openid profile email",...e.audience===void 0?{}:{audience:e.audience},...e.browserLoginOverrides??{}},gateway:e.gateway})}catch(s){let c=s instanceof Error?` Validation failed: ${s.message}`:"";throw new ue(`MCP Auth0 OAuth policy "${t}" is misconfigured. Check the policy options in policies.json.${c}`,s instanceof Error?{cause:s}:void 0)}}o(Tf,"buildAuth0McpOAuthRuntimeConfig");var Kc=class extends vn{static{o(this,"McpOAuthInboundPolicy")}#t;constructor(t,r){let n=Jc(t,r);super(n,r),this.#t=n}async handler(t,r){return Rt("policy.inbound.mcp-oauth"),bn(r,this.#t),xo(t,r)}};function Jc(e,t="mcp-oauth-inbound"){return ii(fc,e,`MCP OAuth policy "${t}"`)}o(Jc,"mcpOAuthOptionsToRuntimeConfig");var Wc=["mcp-oauth-inbound","mcp-auth0-oauth-inbound"];function hR(e,t){switch(e){case"mcp-oauth-inbound":return Jc(t);case"mcp-auth0-oauth-inbound":return kf(t);default:return}}o(hR,"parseMcpOAuthPolicyConfig");function ko(e){return e!==void 0&&Wc.some(t=>t===e)}o(ko,"isMcpOAuthInboundPolicyType");function Af(e){if(e){for(let t of e)if(ko(t.policyType))try{let r=hR(t.policyType,t.handler.options);if(!r)throw new ue(`MCP gateway: policy '${t.name}' has unsupported MCP OAuth policy type '${t.policyType}'.`);return{policyName:t.name,config:r}}catch(r){throw r instanceof u.ZodError?new ue(gR(t.name,r),{cause:r}):r}}}o(Af,"resolveMcpOAuthRuntimeConfigFromPolicies");function gR(e,t){let r=t.issues.map(n=>` - ${n.path.length>0?n.path.join("."):"<root>"}: ${n.message}`).join(`
|
|
35
|
-
`);return`MCP
|
|
36
|
-
${r}`}o(gR,"formatPolicyConfigError");ae();var sr="2025-11-25",Ef="2025-03-26",cr=[sr,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],ur="io.modelcontextprotocol/related-task",ci="2.0",Ie=em(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Uf=fe([f(),X().int()]),Of=f(),TD=Ce({ttl:X().optional(),pollInterval:X().optional()}),SR=I({ttl:X().optional()}),vR=I({taskId:f()}),Yc=Ce({progressToken:Uf.optional(),[ur]:vR.optional()}),nt=I({_meta:Yc.optional()}),To=nt.extend({task:SR.optional()}),$f=o(e=>To.safeParse(e).success,"isTaskAugmentedRequestParams"),Te=I({method:f(),params:nt.loose().optional()}),ut=I({_meta:Yc.optional()}),dt=I({method:f(),params:ut.loose().optional()}),Ae=Ce({_meta:Yc.optional()}),ui=fe([f(),X().int()]),zf=I({jsonrpc:U(ci),id:ui,...Te.shape}).strict(),It=o(e=>zf.safeParse(e).success,"isJSONRPCRequest"),Mf=I({jsonrpc:U(ci),...dt.shape}).strict(),qf=o(e=>Mf.safeParse(e).success,"isJSONRPCNotification"),Qc=I({jsonrpc:U(ci),id:ui,result:Ae}).strict(),gt=o(e=>Qc.safeParse(e).success,"isJSONRPCResultResponse");var E;(function(e){e[e.ConnectionClosed=-32e3]="ConnectionClosed",e[e.RequestTimeout=-32001]="RequestTimeout",e[e.ParseError=-32700]="ParseError",e[e.InvalidRequest=-32600]="InvalidRequest",e[e.MethodNotFound=-32601]="MethodNotFound",e[e.InvalidParams=-32602]="InvalidParams",e[e.InternalError=-32603]="InternalError",e[e.UrlElicitationRequired=-32042]="UrlElicitationRequired"})(E||(E={}));var Xc=I({jsonrpc:U(ci),id:ui.optional(),error:I({code:X().int(),message:f(),data:_e().optional()})}).strict();var En=o(e=>Xc.safeParse(e).success,"isJSONRPCErrorResponse");var Dr=fe([zf,Mf,Qc,Xc]),AD=fe([Qc,Xc]),Lt=Ae.strict(),_R=ut.extend({requestId:ui.optional(),reason:f().optional()}),di=dt.extend({method:U("notifications/cancelled"),params:_R}),wR=I({src:f(),mimeType:f().optional(),sizes:C(f()).optional(),theme:rt(["light","dark"]).optional()}),Ao=I({icons:C(wR).optional()}),An=I({name:f(),title:f().optional()}),Un=An.extend({...An.shape,...Ao.shape,version:f(),websiteUrl:f().optional(),description:f().optional()}),bR=pc(I({applyDefaults:oe().optional()}),de(f(),_e())),RR=mc(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,pc(I({form:bR.optional(),url:Ie.optional()}),de(f(),_e()).optional())),CR=Ce({list:Ie.optional(),cancel:Ie.optional(),requests:Ce({sampling:Ce({createMessage:Ie.optional()}).optional(),elicitation:Ce({create:Ie.optional()}).optional()}).optional()}),IR=Ce({list:Ie.optional(),cancel:Ie.optional(),requests:Ce({tools:Ce({call:Ie.optional()}).optional()}).optional()}),PR=I({experimental:de(f(),Ie).optional(),sampling:I({context:Ie.optional(),tools:Ie.optional()}).optional(),elicitation:RR.optional(),roots:I({listChanged:oe().optional()}).optional(),tasks:CR.optional(),extensions:de(f(),Ie).optional()}),xR=nt.extend({protocolVersion:f(),capabilities:PR,clientInfo:Un}),li=Te.extend({method:U("initialize"),params:xR}),eu=o(e=>li.safeParse(e).success,"isInitializeRequest"),kR=I({experimental:de(f(),Ie).optional(),logging:Ie.optional(),completions:Ie.optional(),prompts:I({listChanged:oe().optional()}).optional(),resources:I({subscribe:oe().optional(),listChanged:oe().optional()}).optional(),tools:I({listChanged:oe().optional()}).optional(),tasks:IR.optional(),extensions:de(f(),Ie).optional()}),tu=Ae.extend({protocolVersion:f(),capabilities:kR,serverInfo:Un,instructions:f().optional()}),pi=dt.extend({method:U("notifications/initialized"),params:ut.optional()}),Nf=o(e=>pi.safeParse(e).success,"isInitializedNotification"),mi=Te.extend({method:U("ping"),params:nt.optional()}),TR=I({progress:X(),total:Se(X()),message:Se(f())}),AR=I({...ut.shape,...TR.shape,progressToken:Uf}),fi=dt.extend({method:U("notifications/progress"),params:AR}),ER=nt.extend({cursor:Of.optional()}),Eo=Te.extend({params:ER.optional()}),Uo=Ae.extend({nextCursor:Of.optional()}),UR=rt(["working","input_required","completed","failed","cancelled"]),Oo=I({taskId:f(),status:UR,ttl:fe([X(),Qp()]),createdAt:f(),lastUpdatedAt:f(),pollInterval:Se(X()),statusMessage:Se(f())}),Bt=Ae.extend({task:Oo}),OR=ut.merge(Oo),$o=dt.extend({method:U("notifications/tasks/status"),params:OR}),hi=Te.extend({method:U("tasks/get"),params:nt.extend({taskId:f()})}),gi=Ae.merge(Oo),yi=Te.extend({method:U("tasks/result"),params:nt.extend({taskId:f()})}),ED=Ae.loose(),Si=Eo.extend({method:U("tasks/list")}),vi=Uo.extend({tasks:C(Oo)}),_i=Te.extend({method:U("tasks/cancel"),params:nt.extend({taskId:f()})}),Df=Ae.merge(Oo),jf=I({uri:f(),mimeType:Se(f()),_meta:de(f(),_e()).optional()}),Hf=jf.extend({text:f()}),ru=f().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Lf=jf.extend({blob:ru}),zo=rt(["user","assistant"]),On=I({audience:C(zo).optional(),priority:X().min(0).max(1).optional(),lastModified:Wp.datetime({offset:!0}).optional()}),Bf=I({...An.shape,...Ao.shape,uri:f(),description:Se(f()),mimeType:Se(f()),size:Se(X()),annotations:On.optional(),_meta:Se(Ce({}))}),$R=I({...An.shape,...Ao.shape,uriTemplate:f(),description:Se(f()),mimeType:Se(f()),annotations:On.optional(),_meta:Se(Ce({}))}),nu=Eo.extend({method:U("resources/list")}),ou=Uo.extend({resources:C(Bf)}),au=Eo.extend({method:U("resources/templates/list")}),iu=Uo.extend({resourceTemplates:C($R)}),su=nt.extend({uri:f()}),zR=su,cu=Te.extend({method:U("resources/read"),params:zR}),uu=Ae.extend({contents:C(fe([Hf,Lf]))}),du=dt.extend({method:U("notifications/resources/list_changed"),params:ut.optional()}),MR=su,qR=Te.extend({method:U("resources/subscribe"),params:MR}),NR=su,DR=Te.extend({method:U("resources/unsubscribe"),params:NR}),jR=ut.extend({uri:f()}),HR=dt.extend({method:U("notifications/resources/updated"),params:jR}),LR=I({name:f(),description:Se(f()),required:Se(oe())}),BR=I({...An.shape,...Ao.shape,description:Se(f()),arguments:Se(C(LR)),_meta:Se(Ce({}))}),lu=Eo.extend({method:U("prompts/list")}),pu=Uo.extend({prompts:C(BR)}),GR=nt.extend({name:f(),arguments:de(f(),f()).optional()}),mu=Te.extend({method:U("prompts/get"),params:GR}),fu=I({type:U("text"),text:f(),annotations:On.optional(),_meta:de(f(),_e()).optional()}),hu=I({type:U("image"),data:ru,mimeType:f(),annotations:On.optional(),_meta:de(f(),_e()).optional()}),gu=I({type:U("audio"),data:ru,mimeType:f(),annotations:On.optional(),_meta:de(f(),_e()).optional()}),VR=I({type:U("tool_use"),name:f(),id:f(),input:de(f(),_e()),_meta:de(f(),_e()).optional()}),FR=I({type:U("resource"),resource:fe([Hf,Lf]),annotations:On.optional(),_meta:de(f(),_e()).optional()}),ZR=Bf.extend({type:U("resource_link")}),yu=fe([fu,hu,gu,ZR,FR]),KR=I({role:zo,content:yu}),Su=Ae.extend({description:f().optional(),messages:C(KR)}),vu=dt.extend({method:U("notifications/prompts/list_changed"),params:ut.optional()}),JR=I({title:f().optional(),readOnlyHint:oe().optional(),destructiveHint:oe().optional(),idempotentHint:oe().optional(),openWorldHint:oe().optional()}),WR=I({taskSupport:rt(["required","optional","forbidden"]).optional()}),Gf=I({...An.shape,...Ao.shape,description:f().optional(),inputSchema:I({type:U("object"),properties:de(f(),Ie).optional(),required:C(f()).optional()}).catchall(_e()),outputSchema:I({type:U("object"),properties:de(f(),Ie).optional(),required:C(f()).optional()}).catchall(_e()).optional(),annotations:JR.optional(),execution:WR.optional(),_meta:de(f(),_e()).optional()}),_u=Eo.extend({method:U("tools/list")}),wu=Uo.extend({tools:C(Gf)}),dr=Ae.extend({content:C(yu).default([]),structuredContent:de(f(),_e()).optional(),isError:oe().optional()}),UD=dr.or(Ae.extend({toolResult:_e()})),YR=To.extend({name:f(),arguments:de(f(),_e()).optional()}),Mo=Te.extend({method:U("tools/call"),params:YR}),bu=dt.extend({method:U("notifications/tools/list_changed"),params:ut.optional()}),Vf=I({autoRefresh:oe().default(!0),debounceMs:X().int().nonnegative().default(300)}),qo=rt(["debug","info","notice","warning","error","critical","alert","emergency"]),QR=nt.extend({level:qo}),Ru=Te.extend({method:U("logging/setLevel"),params:QR}),XR=ut.extend({level:qo,logger:f().optional(),data:_e()}),eC=dt.extend({method:U("notifications/message"),params:XR}),tC=I({name:f().optional()}),rC=I({hints:C(tC).optional(),costPriority:X().min(0).max(1).optional(),speedPriority:X().min(0).max(1).optional(),intelligencePriority:X().min(0).max(1).optional()}),nC=I({mode:rt(["auto","required","none"]).optional()}),oC=I({type:U("tool_result"),toolUseId:f().describe("The unique identifier for the corresponding tool call."),content:C(yu).default([]),structuredContent:I({}).loose().optional(),isError:oe().optional(),_meta:de(f(),_e()).optional()}),aC=lc("type",[fu,hu,gu]),si=lc("type",[fu,hu,gu,VR,oC]),iC=I({role:zo,content:fe([si,C(si)]),_meta:de(f(),_e()).optional()}),sC=To.extend({messages:C(iC),modelPreferences:rC.optional(),systemPrompt:f().optional(),includeContext:rt(["none","thisServer","allServers"]).optional(),temperature:X().optional(),maxTokens:X().int(),stopSequences:C(f()).optional(),metadata:Ie.optional(),tools:C(Gf).optional(),toolChoice:nC.optional()}),Cu=Te.extend({method:U("sampling/createMessage"),params:sC}),jr=Ae.extend({model:f(),stopReason:Se(rt(["endTurn","stopSequence","maxTokens"]).or(f())),role:zo,content:aC}),No=Ae.extend({model:f(),stopReason:Se(rt(["endTurn","stopSequence","maxTokens","toolUse"]).or(f())),role:zo,content:fe([si,C(si)])}),cC=I({type:U("boolean"),title:f().optional(),description:f().optional(),default:oe().optional()}),uC=I({type:U("string"),title:f().optional(),description:f().optional(),minLength:X().optional(),maxLength:X().optional(),format:rt(["email","uri","date","date-time"]).optional(),default:f().optional()}),dC=I({type:rt(["number","integer"]),title:f().optional(),description:f().optional(),minimum:X().optional(),maximum:X().optional(),default:X().optional()}),lC=I({type:U("string"),title:f().optional(),description:f().optional(),enum:C(f()),default:f().optional()}),pC=I({type:U("string"),title:f().optional(),description:f().optional(),oneOf:C(I({const:f(),title:f()})),default:f().optional()}),mC=I({type:U("string"),title:f().optional(),description:f().optional(),enum:C(f()),enumNames:C(f()).optional(),default:f().optional()}),fC=fe([lC,pC]),hC=I({type:U("array"),title:f().optional(),description:f().optional(),minItems:X().optional(),maxItems:X().optional(),items:I({type:U("string"),enum:C(f())}),default:C(f()).optional()}),gC=I({type:U("array"),title:f().optional(),description:f().optional(),minItems:X().optional(),maxItems:X().optional(),items:I({anyOf:C(I({const:f(),title:f()}))}),default:C(f()).optional()}),yC=fe([hC,gC]),SC=fe([mC,fC,yC]),vC=fe([SC,cC,uC,dC]),_C=To.extend({mode:U("form").optional(),message:f(),requestedSchema:I({type:U("object"),properties:de(f(),vC),required:C(f()).optional()})}),wC=To.extend({mode:U("url"),message:f(),elicitationId:f(),url:f().url()}),bC=fe([_C,wC]),Iu=Te.extend({method:U("elicitation/create"),params:bC}),RC=ut.extend({elicitationId:f()}),CC=dt.extend({method:U("notifications/elicitation/complete"),params:RC}),lr=Ae.extend({action:rt(["accept","decline","cancel"]),content:mc(e=>e===null?void 0:e,de(f(),fe([f(),X(),oe(),C(f())])).optional())}),IC=I({type:U("ref/resource"),uri:f()});var PC=I({type:U("ref/prompt"),name:f()}),xC=nt.extend({ref:fe([PC,IC]),argument:I({name:f(),value:f()}),context:I({arguments:de(f(),f()).optional()}).optional()}),kC=Te.extend({method:U("completion/complete"),params:xC});var Pu=Ae.extend({completion:Ce({values:C(f()).max(100),total:Se(X().int()),hasMore:Se(oe())})}),TC=I({uri:f().startsWith("file://"),name:f().optional(),_meta:de(f(),_e()).optional()}),AC=Te.extend({method:U("roots/list"),params:nt.optional()}),xu=Ae.extend({roots:C(TC)}),EC=dt.extend({method:U("notifications/roots/list_changed"),params:ut.optional()}),OD=fe([mi,li,kC,Ru,mu,lu,nu,au,cu,qR,DR,Mo,_u,hi,yi,Si,_i]),$D=fe([di,fi,pi,EC,$o]),zD=fe([Lt,jr,No,lr,xu,gi,vi,Bt]),MD=fe([mi,Cu,Iu,AC,hi,yi,Si,_i]),qD=fe([di,fi,eC,HR,du,bu,vu,$o,CC]),ND=fe([Lt,tu,Pu,Su,pu,ou,iu,uu,dr,wu,gi,vi,Bt]),x=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 Ht(a.elicitations,r)}return new e(t,r,n)}},Ht=class extends x{static{o(this,"UrlElicitationRequiredError")}constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(E.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};ae();var Kf=Je,UC=u.object({mode:u.literal("auto")}).strict(),OC=u.object({mode:u.literal("manual"),clientId:u.string().trim().min(1),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:hc.default("client_secret_basic")}).strict().superRefine((e,t)=>{e.tokenEndpointAuthMethod!=="none"&&!e.clientSecret&&t.addIssue({code:u.ZodIssueCode.custom,message:`${e.tokenEndpointAuthMethod} requires clientSecret`,path:["clientSecret"]})}),Jf=u.discriminatedUnion("mode",[UC,OC]),$C=Jf.default({mode:"auto"}),ku=u.object({scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:$C}).strict(),Ff=ku.extend({redirectPath:u.string().startsWith("/auth/connections/")}).strict(),Wf=new Set(["connection","content-length","cookie","host","proxy-authenticate","proxy-authorization","sec-websocket-key","set-cookie","te","trailer","transfer-encoding","upgrade"]),zC=new Set([...Wf,"accept","authorization","content-type","mcp-protocol-version","mcp-session-id","proxy-connection"]),MC=u.object({kind:u.literal("bearer_token"),token:u.string().min(1)}).strict(),qC=u.object({kind:u.literal("headers"),headers:u.array(u.object({name:Ka,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();Wf.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)}}),Tu=u.discriminatedUnion("kind",[MC,qC]),NC=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(),DC=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key"),capture:u.enum(["browser_login"]).optional()}).strict(),Au=u.discriminatedUnion("kind",[NC,DC]),Eu=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key")}).strict(),jC=u.discriminatedUnion("mode",[u.object({mode:u.literal("shared-oauth"),oauth:Ff}).strict(),u.object({mode:u.literal("user-oauth"),oauth:Ff}).strict(),u.object({mode:u.literal("static-secret"),secret:Tu}).strict(),u.object({mode:u.literal("user-secret"),secret:Au}).strict(),u.object({mode:u.literal("shared-secret"),secret:Eu}).strict()]),HC=u.object({baseUrl:u.url(),resourceMetadataUrl:u.url(),requestHeaders:u.array(gc).default([])}).strict().superRefine((e,t)=>{let r=new Set;for(let[n,a]of e.requestHeaders.entries()){let i=a.name.toLowerCase();zC.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)}}),VD=u.object({displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:Un.optional(),authProfiles:u.record(We,jC),transport:HC}).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"]})}),LC=u.object({"shared-oauth":ku.optional(),"user-oauth":ku.optional(),"static-secret":u.object({secret:Tu}).strict().optional(),"user-secret":u.object({secret:Au}).strict().optional(),"shared-secret":u.object({secret:Eu}).strict().optional()}).strict().superRefine((e,t)=>{Object.values(e).every(r=>r===void 0)&&t.addIssue({code:u.ZodIssueCode.custom,message:"authProfiles must contain at least one upstream auth profile"})}),Zf=u.object({id:Kf,displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:Un.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url(),requestHeaders:u.array(gc).default([]),authProfiles:LC}).strict(),BC=u.object({name:Ka,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict(),wi={id:Kf.optional(),displayName:u.string().min(1),summary:u.string().min(1).optional(),serverInfo:Un.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url().optional(),requestHeaders:u.array(BC).default([])},GC=u.discriminatedUnion("authMode",[u.object({...wi,authMode:u.enum(["shared-oauth","user-oauth"]),scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:Jf.optional(),clientId:u.string().trim().min(1).optional(),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:hc.optional()}).strict(),u.object({...wi,authMode:u.literal("static-secret"),secret:Tu}).strict(),u.object({...wi,authMode:u.literal("user-secret"),secret:Au}).strict(),u.object({...wi,authMode:u.literal("shared-secret"),secret:Eu}).strict()]);function VC(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
|
|
37
|
-
`)}o(
|
|
38
|
-
${VC(r)}`,{cause:r})}throw r}}o(bi,"parseUpstreamConnectionPolicyOptions");function Qf(e){return e.mode==="shared-oauth"||e.mode==="user-oauth"}o(Qf,"isUpstreamOAuthAuthConfig");ae();var KC=u.looseObject({name:u.string().min(1),version:u.string().min(1).optional()}),JC=u.looseObject({}),WC=u.looseObject({name:ar,namespace:ar.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional(),inputSchema:JC}),YC=u.looseObject({name:ar,namespace:ar.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional()}),QC=u.looseObject({name:ar,uri:u.string().min(1),upstreamPolicy:u.string().min(1).optional(),upstreamUri:u.string().min(1).optional(),enabled:u.boolean().optional()}),XC=u.enum(["openapi","upstream_mcp"]),eI=u.object({catalogSource:XC.default("openapi"),serverInfo:KC.optional(),tools:u.array(WC).default([]),prompts:u.array(YC).default([]),resources:u.array(QC).default([])}).strict();function tI(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
|
|
39
|
-
`)}o(tI,"formatZodIssues");function Xf(e,t){try{return eI.parse(e??{})}catch(r){if(r instanceof u.ZodError){let n=t===void 0?"MCP virtual server route":`MCP virtual server route ${t}`;throw new ue(`${n} is misconfigured. Missing/invalid handler options in routes.oas.json:
|
|
40
|
-
${tI(r)}`,{cause:r})}throw r}}o(Xf,"parseVirtualServerRouteOptions");function Ri(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(Ri,"toMcpTool");function Ci(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(Ci,"toMcpPrompt");function Ii(e){let{enabled:t,upstreamPolicyName:r,upstreamUri:n,...a}=e;return a}o(Ii,"toMcpResource");var rI="mcp-upstream-connection-inbound",eh="/mcp/";function Be(e){throw new ue(e)}o(Be,"throwRegistryError");function nI(e){return e.policyType===rI}o(nI,"isUpstreamConnectionPolicy");function oI(e){return ko(e.policyType)}o(oI,"isMcpOAuthInboundPolicy");function aI(e){return e instanceof ue?e:new ue(e instanceof Error?e.message:"MCP virtual server route is misconfigured.",e instanceof Error?{cause:e}:void 0)}o(aI,"toRouteConfigurationError");function iI(e){e.startsWith(eh)||Be(`MCP virtual server route ${e} must use a /mcp/{virtualServerId} path.`);let t=e.slice(eh.length);return(!t||t.includes("/"))&&Be(`MCP virtual server route ${e} must use exactly one /mcp/{virtualServerId} path segment.`),xe.parse(t)}o(iI,"readVirtualServerIdFromPath");function sI(e){let t=Object.keys(e.connection.authProfiles);t.length!==1&&Be(`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];return r===void 0&&Be(`Upstream policy ${e.policyName} does not declare an auth mode.`),Za.parse(r)}o(sI,"readSingleAuthMode");function cI(e){let t=e.connection.authProfiles[e.authMode];t||Be(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`);let r=`/auth/connections/${encodeURIComponent(e.connection.id)}/callback`;switch(e.authMode){case"shared-oauth":case"user-oauth":{let n=t;return{mode:e.authMode,oauth:{scopes:n.scopes,scopeDelimiter:n.scopeDelimiter,redirectPath:r,clientRegistration:n.clientRegistration}}}case"static-secret":return{mode:"static-secret",secret:t.secret};case"user-secret":return{mode:"user-secret",secret:t.secret};case"shared-secret":return{mode:"shared-secret",secret:t.secret}}}o(cI,"buildResolvedAuthConfig");function uI(e){let t=sI({policyName:e.policyName,connection:e.connection}),r=$n(e.connection.id,t),n=cI({connection:e.connection,authMode:t,authProfileId:r}),a={displayName:e.connection.displayName,...e.connection.description===void 0?{}:{description:e.connection.description},...e.connection.serverInfo===void 0?{}:{serverInfo:e.connection.serverInfo},authProfiles:{[r]:n},transport:{baseUrl:e.connection.mcpUrl,resourceMetadataUrl:e.connection.protectedResourceMetadataUrl,requestHeaders:e.connection.requestHeaders}};return{policyName:e.policyName,upstreamServerId:e.connection.id,config:a,authMode:t,authProfileId:r,authConfig:n}}o(uI,"buildRegisteredConnection");function dI(e){let t=new Map;for(let r of e)t.has(r.name)&&Be(`Duplicate policy name ${r.name} in policies.json.`),t.set(r.name,{name:r.name,policyType:r.policyType,handler:{options:r.handler.options}});return t}o(dI,"buildPolicyMap");function lI(e){if(typeof e.raw!="function")return;let t=e.raw();if(!(!t||typeof t.operationId!="string"||t.operationId===""))return t.operationId}o(lI,"readOperationId");function th(e){let t=e.namespace===void 0?e.name:`${e.namespace}.${e.name}`;try{return ar.parse(t)}catch{Be(`MCP virtual server route ${e.routePath} declares invalid published capability name ${t}.`)}}o(th,"buildPublishedCapabilityName");function $u(e){if(e.authoredPolicyName!==void 0)return e.connections.find(r=>r.policyName===e.authoredPolicyName)||Be(`MCP virtual server route ${e.routePath} declares capability ${e.capabilityName} for upstream policy ${e.authoredPolicyName}, but that policy is not bound to the route.`),e.authoredPolicyName;if(e.connections.length===1)return e.connections[0]?.policyName;Be(`MCP virtual server route ${e.routePath} declares aggregate capability ${e.capabilityName} without upstreamPolicy.`)}o($u,"readCapabilityUpstreamPolicy");function Uu(e){e.seen.has(e.key)&&Be(`MCP virtual server route ${e.routePath} declares duplicate ${e.kind} ${e.key}.`),e.seen.add(e.key)}o(Uu,"assertUniqueCatalogKey");function pI(e){let{namespace:t,upstreamPolicy:r,...n}=e.tool,a=th({name:e.tool.name,namespace:e.tool.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.tool.name,upstreamPolicyName:$u({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(pI,"normalizeCatalogTool");function mI(e){let{namespace:t,upstreamPolicy:r,...n}=e.prompt,a=th({name:e.prompt.name,namespace:e.prompt.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.prompt.name,upstreamPolicyName:$u({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(mI,"normalizeCatalogPrompt");function fI(e){let{upstreamPolicy:t,...r}=e.resource;return{...r,upstreamUri:e.resource.upstreamUri??e.resource.uri,upstreamPolicyName:$u({authoredPolicyName:t,capabilityName:e.resource.uri,connections:e.connections,routePath:e.routePath})}}o(fI,"normalizeCatalogResource");function hI(e){let t=e.catalog.catalogSource,r=e.catalog.tools.map(d=>pI({tool:d,connections:e.connections,routePath:e.routePath})),n=e.catalog.prompts.map(d=>mI({prompt:d,connections:e.connections,routePath:e.routePath})),a=e.catalog.resources.map(d=>fI({resource:d,connections:e.connections,routePath:e.routePath})),i=new Set;for(let d of r)Uu({kind:"tool",key:d.name,routePath:e.routePath,seen:i});let s=new Set;for(let d of n)Uu({kind:"prompt",key:d.name,routePath:e.routePath,seen:s});let c=new Set;for(let d of a)Uu({kind:"resource",key:String(d.uri),routePath:e.routePath,seen:c});return{catalogSource:t,...e.catalog.serverInfo===void 0?{}:{serverInfo:e.catalog.serverInfo},tools:r,prompts:n,resources:a}}o(hI,"normalizeVirtualServerCatalog");function gI(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=bi(c.handler.options,c.name);a.has(p.id)&&Be(`Duplicate upstream MCP connection id ${p.id} in policies.json.`),a.add(p.id);let l=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||!oI(l))continue;let m=lI(c),h;try{h=iI(c.path),m||Be(`MCP virtual server route ${c.path} must declare an operationId in routes.oas.json.`),i.has(m)&&Be(`Duplicate MCP virtual server operationId ${m} across routes.`),t.has(h)&&Be(`Duplicate MCP virtual server id ${h} across routes.`);let y=[];for(let _ of d.slice(1)){let w=e.policyByName.get(_);!w||!nI(w)||y.push(s(w))}let v=Xf(c.handler.options,c.path),S=hI({catalog:v,connections:y,routePath:c.path});S.catalogSource==="upstream_mcp"&&y.length!==1&&Be(`MCP virtual server route ${c.path} uses upstream MCP catalog mode but declares ${y.length} upstream bindings; upstream MCP catalog mode requires exactly one upstream binding.`),t.set(h,{virtualServerId:h,operationId:m,routePath:c.path,handlerExport:c.handler.export,serverInfo:S.serverInfo,catalog:S,connections:y}),i.add(m)}catch(y){h!==void 0&&r.set(h,aI(y))}}return{byVirtualServerId:t,virtualServerErrorsById:r,connectionsByPolicyName:n}}o(gI,"buildVirtualServers");function zu(e){let t=dI(e.policies),{byVirtualServerId:r,virtualServerErrorsById:n,connectionsByPolicyName:a}=gI({routes:e.routes,policyByName:t}),i=new Map;for(let s of a.values())i.set(s.upstreamServerId,s);return{byVirtualServerId:r,connectionsById:i,virtualServerErrorsById:n}}o(zu,"buildGatewayConnectionRegistry");var Hr,Ou;function rh(e){Ou=e,Hr=void 0}o(rh,"configureGatewayConnectionRegistrySource");function nh(e){Hr=e}o(nh,"setGatewayConnectionRegistry");function yt(){if(!Hr&&Ou&&(Hr=zu(Ou)),!Hr)throw g("internal_server_error","MCP gateway connection registry has not been initialized. Ensure routes.oas.json declares at least one MCP virtual server route and policies.json registers an `mcp-oauth-inbound` (or wrapper) policy.");return Hr}o(yt,"getGatewayConnectionRegistry");function Mr(e){let t=yt(),r=t.virtualServerErrorsById?.get(e);if(r)throw r;let n=t.byVirtualServerId.get(e);if(!n)throw g("unknown_virtual_server",`Unknown MCP virtual server: ${e}`);return n}o(Mr,"getRegisteredVirtualServer");function oh(){return Hr}o(oh,"tryGetGatewayConnectionRegistry");function De(e){let t=yt().connectionsById.get(e);if(!t)throw g("unknown_upstream_server",`Unknown upstream server: ${e}`);return t.config}o(De,"getUpstreamServerConfig");function yI(e){let t=yt().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw g("unknown_auth_profile",`Unknown auth profile ${String(e.authProfileId)} for upstream server ${e.upstreamServerId}.`);return t.authProfileId}o(yI,"resolveUpstreamAuthProfileId");function pr(e){yI(e);let t=yt().connectionsById.get(e.upstreamServerId);if(!t)throw g("unknown_auth_profile",`Auth profile could not be resolved for upstream server ${e.upstreamServerId}.`);return t.authConfig}o(pr,"getUpstreamAuthConfig");function Lr(e,t){let r=pr({upstreamServerId:e,authProfileId:t});if(!Qf(r))throw g("invalid_request",`Upstream server ${e} does not use upstream OAuth.`);return r.oauth}o(Lr,"requireUpstreamOAuthConfig");function SI(){let e=uc.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP??globalThis.process?.env?.__TEST_ONLY_MCP_GATEWAY_ALLOW_HTTP_LOOPBACK_IDP;return typeof e=="string"&&e==="1"}o(SI,"isTestOnlyAllowHttpLoopbackIdpEnabled");var vI=new Set(["undefined","null","nan"]);function qu(e,t){if(!e.hostname)throw g("invalid_request",`Outbound URL has an empty hostname (got ${JSON.stringify(t)}). This typically indicates an unset $env(...) reference or a JS template literal coercing \`undefined\` into a URL. Check the policy options or runtime config that produced this URL.`);if(vI.has(e.hostname.toLowerCase()))throw g("invalid_request",`Outbound URL hostname is ${JSON.stringify(e.hostname)} (from ${JSON.stringify(t)}). This almost always means an environment variable referenced by $env(...) is unset and a JS value was string-coerced into a URL. Set the missing env var or fix the policy option that produced this URL.`)}o(qu,"assertSafeOutboundHostname");var _I=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),wI=[{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 ah(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(ah,"parseIpv4Octets");function bI([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(bI,"ipv4RangeMatches");function ih(e){let t=ah(e);return t!==void 0&&wI.some(r=>bI(t,r))}o(ih,"isPrivateIpv4");function Mu(e){if(!e||e.length>4)return;let t=Number.parseInt(e,16);return Number.isNaN(t)||t<0||t>65535?void 0:t}o(Mu,"parseIpv6Word");function RI(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}o(RI,"formatIpv4FromWords");function CI(e){let t=e.slice(7),r=ah(t);if(r!==void 0)return r.join(".");let[n,a,i]=t.split(":"),s=Mu(n),c=Mu(a);return i===void 0&&s!==void 0&&c!==void 0?RI(s,c):void 0}o(CI,"parseIpv6MappedIpv4");function II(e){return Mu(e.split(":").find(Boolean))}o(II,"readFirstIpv6Hextet");function PI(e){let t=Nt(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let n=CI(t);return n===void 0||ih(n)}let r=II(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}o(PI,"isPrivateIpv6");function Nu(e){let t=Nt(e);return _I.has(t)||t.endsWith(".internal")||ih(t)||PI(t)}o(Nu,"isBlockedOutboundHostname");function sh(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw g("invalid_request",`Unsupported outbound protocol: ${t.protocol}`);qu(t,e);let r=qe(t);if(t.protocol==="http:"&&!r)throw g("invalid_request","Configured outbound HTTP URLs must target loopback hosts.");let n=Nt(t.hostname);if(!r&&Nu(n))throw g("invalid_request",`Blocked outbound host: ${n}`);return t}o(sh,"validateConfiguredOutboundUrl");function ch(e){let t=new URL(e),r=qe(t),n=r&&SI();if(t.protocol!=="https:"&&!n)throw g("invalid_request","Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw g("invalid_request","Identity provider URLs must not include credentials, query params, or fragments.");qu(t,e);let a=Nt(t.hostname);if(!r&&Nu(a))throw g("invalid_request",`Blocked identity provider host: ${a}`);return t}o(ch,"validateIdentityProviderUrl");function Pi(e){let t=new URL(e);if(t.protocol!=="https:"||t.pathname==="/"||t.username||t.password||t.search||t.hash)throw g("invalid_request","CIMD client_id must be an HTTPS URL with a path and no credentials, query, or fragment.");if(qu(t,e),Nu(t.hostname))throw g("invalid_request","CIMD client_id points at a blocked host.");return t}o(Pi,"validateCimdClientMetadataUrl");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 xI(e){try{await e.cancel()}catch{}}o(xI,"cancelReader");async function xi(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 xI(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(xi,"readBoundedByteStream");var kI=2,TI=1024*1024,AI=1e4,EI=new Set([301,302,303,307,308]),UI=["authorization","proxy-authorization","cookie","cookie2"];function Du(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(Du,"readRequestUrl");function zn(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(zn,"readRequestMethod");function OI(e,t,r){let n=e.headers.get("content-length");if(!n)return;let a=Number.parseInt(n,10);if(Number.isFinite(a)&&a>t)throw g(r,"Outbound response exceeded the maximum allowed size.")}o(OI,"assertContentLengthWithinLimit");async function $I(e,t,r){return OI(e,t,r),xi(e.body,{maxBytes:t,createLimitError:o(()=>g(r,"Outbound response exceeded the maximum allowed size."),"createLimitError")})}o($I,"readBoundedResponseBody");function zI(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(zI,"responseFromBufferedBody");function MI(e,t){if(!EI.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(MI,"resolveRedirectUrl");function dh(e,t){try{return t.validateUrl(e)}catch(r){throw g(t.problemCode,"Outbound URL was not allowed.",r)}}o(dh,"validateOutboundUrl");function qI(e,t){throw ge(e)!==void 0?e:g(t,"Outbound fetch failed.",e)}o(qI,"normalizeFetchError");function Do(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[n,a]of Object.entries(t.extra))a!==void 0&&(r[n]=a);t.error!==void 0&&Ye(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o(Do,"logOutboundFailure");async function NI(e,t,r,n,a,i,s){let c=zn(r,n);try{return await t(r,n)}catch(d){let p=d instanceof DOMException&&d.name==="AbortError";Do(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:c,host:st(i),error:d,extra:{abortReason:s()}}),qI(d,a)}}o(NI,"fetchWithNormalizedError");function DI(e){if(e.redirects>=e.maxRedirects)throw g(e.problemCode,"Outbound redirects exceeded the maximum allowed depth.");if(e.method!=="GET"&&e.method!=="HEAD")throw g(e.problemCode,"Outbound redirect after a non-idempotent request was blocked.")}o(DI,"assertRedirectAllowed");function jI(e,t){let r=new Headers(e);for(let n of UI)r.delete(n);for(let n of t)r.delete(n);return r}o(jI,"stripCrossOriginHeaders");function HI(e,t,r,n,a){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=jI(e.headers,a)),i}o(HI,"buildRedirectInit");function LI(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(LI,"buildInitialRequestInit");function BI(e){let t=zn(e.currentInput,e.currentInit);DI({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:HI(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(BI,"followRedirect");async function ju(e,t,r){let n=r.problemCode??"invalid_request",a=r.maxRedirects??kI,i=r.maxResponseBytes??TI,s=r.timeoutMs??AI,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],p=r.context,l=new AbortController,m=uh(l,t.signal),h=!1,y=setTimeout(()=>{h=!0,l.abort()},s),v=e,S=LI(e,t,l.signal),_;try{_=dh(Du(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(b){throw Do(p,{event:"outbound_url_blocked",problemCode:n,method:zn(e,t),host:st(Du(e)),error:b}),clearTimeout(y),m?.(),b}let w=0;try{for(;;){let b=await NI(p,c,v,S,n,_,()=>h?`timeout_after_${s}ms`:void 0),R=MI(b,_);if(R!==void 0)try{let z=BI({currentInput:v,currentInit:S,currentUrl:_,redirectUrl:R,redirects:w,maxRedirects:a,problemCode:n,validateUrl:r.validateUrl,signal:l.signal,additionalCrossOriginStrippedHeaders:d});v=z.currentInput,S=z.currentInit,_=z.currentUrl,w=z.redirects;continue}catch(z){throw Do(p,{event:"outbound_redirect_blocked",problemCode:n,method:zn(v,S),host:st(_),error:z,extra:{redirects:w,maxRedirects:a,redirectTargetHost:st(R)}}),z}try{return zI(b,await $I(b,i,n))}catch(z){throw Do(p,{event:"outbound_response_size_exceeded",problemCode:n,method:zn(v,S),host:st(_),error:z,extra:{maxResponseBytes:i,status:b.status}}),z}}}finally{clearTimeout(y),m?.()}}o(ju,"runSafeOutboundExchange");async function Hu(e,t,r){let n=await ju(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(a){throw Do(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:zn(e,t),host:st(Du(e)),error:a,extra:{status:n.status,contentType:n.headers.get("content-type")??void 0}}),g(r.problemCode??"invalid_request","Outbound JSON response could not be parsed.",a)}}o(Hu,"runSafeOutboundJsonExchange");function Mn(e,t={},r={}){return ju(e,t,{...r,validateUrl:sh})}o(Mn,"fetchConfiguredOutbound");function lh(e,t={},r={}){return Hu(e,t,{...r,validateUrl:ch})}o(lh,"fetchIdentityProviderJson");function ph(e,t={},r={}){return Hu(e,t,{...r,validateUrl:Pi})}o(ph,"fetchCimdClientMetadataJson");var GI={"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 Pt(e){return GI[e]}o(Pt,"describeUpstreamAuthMode");function ki(e){return Pt(e).ownerMode}o(ki,"resolveOwnerModeForUpstreamAuthMode");ae();import{errors as _h,jwtVerify as wh,SignJWT as bh}from"jose";import{base64url as VI}from"jose";var FI=new TextEncoder,ZI="MCP gateway could not initialize secure key material.",KI=32,mh=new Map,fh=new Map,JI;function WI(){return JI??So.instance.authPrivateKey}o(WI,"readAuthPrivateKey");function hh(e){return new Sn(ZI,e===void 0?void 0:{cause:e})}o(hh,"createGeneratedKeyMaterialError");function gh(e,t){let r=VI.decode(t);if(r.byteLength!==KI)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}o(gh,"decodeJwkKeyField");function YI(e){let t=WI();if(!t)throw hh();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=gh("d",r.d);gh("x",r.x);let a=FI.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 hh(r)}}o(YI,"decodeGeneratedKeyMaterial");function QI(e){let t=mh.get(e);return t||(t=YI(e),mh.set(e,t)),t}o(QI,"getMasterKeyMaterial");async function xt(e){let t=fh.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(QI(e.keyMaterialPurpose));return fh.set(e.purpose,r),r}o(xt,"readCachedDerivedKey");var XI="SHA-256";var eP="zuplo-mcp-gateway:",tP=new TextEncoder,yh=new WeakMap;async function mr(e,t){let r=yh.get(e);r||(r=new Map,yh.set(e,r));let n=r.get(t);if(n)return n;let a=await rP(e,t);return r.set(t,a),a}o(mr,"deriveGatewaySigningKey");async function rP(e,t){let r=Sh(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=tP.encode(`${eP}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:XI,salt:new Uint8Array,info:Sh(a)},n,32*8);return new Uint8Array(i)}o(rP,"hkdfExpand");function Sh(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Sh,"copyToArrayBuffer");var Ti="HS256",Rh=15*60,nP=15*60,Ai="zuplo-mcp-gateway",Ei="zuplo-mcp-gateway",oP=Am.extend({id:xn}),aP=oP.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),Ch=In.extend({id:Po,purpose:u.literal("browser_connect")}),iP=In.extend({purpose:u.literal("browser_connect")}),sP=Ch.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),Ih=Rh*1e3;async function Ph(){return xt({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>mr(e,"oauth-state"),"derive")})}o(Ph,"getOAuthStateKey");async function xh(){return xt({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>mr(e,"browser-connect"),"derive")})}o(xh,"getBrowserConnectKey");async function kh(e){let t=Math.floor(Date.now()/1e3)+Rh;return new bh(e).setProtectedHeader({alg:Ti,typ:"JWT"}).setIssuer(Ai).setAudience(Ei).setIssuedAt().setExpirationTime(t).sign(await Ph())}o(kh,"signOAuthState");async function Ui(e){try{let{payload:t}=await wh(e,await Ph(),{algorithms:[Ti],issuer:Ai,audience:Ei});return aP.parse(t)}catch(t){throw t instanceof _h.JWTExpired?g("oauth_state_expired","OAuth state has expired",t):g("oauth_state_invalid","OAuth state could not be verified",t)}}o(Ui,"verifyOAuthState");async function Th(e){let t=Math.floor(Date.now()/1e3)+nP,r=iP.parse(e),n=Ch.parse({...r,id:zm()});return new bh(n).setProtectedHeader({alg:Ti,typ:"JWT"}).setIssuer(Ai).setAudience(Ei).setIssuedAt().setExpirationTime(t).sign(await xh())}o(Th,"signBrowserConnectTicket");async function Oi(e){try{let{payload:t}=await wh(e,await xh(),{algorithms:[Ti],issuer:Ai,audience:Ei});return sP.parse(t)}catch(t){throw t instanceof _h.JWTExpired?g("oauth_state_expired","Browser connect ticket has expired",t):g("oauth_state_invalid","Browser connect ticket could not be verified",t)}}o(Oi,"verifyBrowserConnectTicket");async function $i(e){if((await K().consumeBrowserConnectTicket({id:e.id,expiresAt:re(new Date(e.exp*1e3)),now:re(new Date)})).kind==="consumed")throw g("oauth_state_reused","Browser connect ticket has already been used")}o($i,"consumeBrowserConnectTicket");function cP(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(cP,"buildConnectRequiredMessage");async function Ah(e){let t=ie(e.requestUrl),r=new URL(e.path,t);return e.redirect&&r.searchParams.set("redirect","true"),r.searchParams.set("virtualServerId",e.virtualServerId),r.searchParams.set("browserTicket",await Th({...Io(e),purpose:"browser_connect"})),r.toString()}o(Ah,"buildGatewayBrowserTicketUrl");function uP(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}o(uP,"buildGatewayConnectPath");async function Lu(e){return Ah({...e,path:uP(e.upstreamServerId),redirect:!0})}o(Lu,"buildGatewayConnectUrl");async function Eh(e){return Ah({...e,path:`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`})}o(Eh,"buildGatewayAppPasswordCaptureUrl");async function qn(e){let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await Lu(t),message:cP(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(qn,"buildRedirectConnectRequiredResponse");function Uh(e){return Oh({...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(Uh,"buildAdminConnectRequiredResponse");function Oh(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(Oh,"buildAdminSetupRequiredResponse");function $h(e){return Oh({...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($h,"buildAdminStaticSecretRequiredResponse");ae();import{base64url as fr}from"jose";var dP="SHA-256",Dn="AES-GCM",lP=12,Gu="zuplo-secret",Vu=1,zh="generated:auth_private_key:token-encryption",pP=u.object({version:u.literal(Vu),keyId:u.literal(zh),algorithm:u.literal(Dn),iv:u.string().min(1),ciphertext:u.string().min(1)}).strict();function Nn(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Nn,"copyToArrayBuffer");async function Bu(){return xt({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:o(async e=>{let t=await crypto.subtle.digest(dP,Nn(e));return crypto.subtle.importKey("raw",t,{name:Dn},!1,["encrypt","decrypt"])},"derive")})}o(Bu,"getEncryptionKey");function Mh(e){return Nn(new TextEncoder().encode(`${Gu}:v${e.version}:${e.keyId}`))}o(Mh,"getAssociatedData");function mP(e){return`${Gu}:v${e.version}:${fr.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(mP,"encodeEnvelope");function fP(e){let t=`${Gu}:v${Vu}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(fr.decode(r));return pP.parse(JSON.parse(n))}o(fP,"decodeEnvelope");async function Br(e){let t=await Bu(),r=crypto.getRandomValues(new Uint8Array(lP)),n={version:Vu,keyId:zh},a=await crypto.subtle.encrypt({name:Dn,iv:r,additionalData:Mh(n)},t,new TextEncoder().encode(e));return mP({...n,algorithm:Dn,iv:fr.encode(r),ciphertext:fr.encode(new Uint8Array(a))})}o(Br,"encryptSecret");async function Gt(e){let t=fP(e);if(t){let s=await Bu(),c=await crypto.subtle.decrypt({name:Dn,iv:Nn(fr.decode(t.iv)),additionalData:Mh(t)},s,Nn(fr.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,n]=e.split(".");if(!r||!n)throw g("internal_server_error","Encrypted payload is malformed");let a=await Bu(),i=await crypto.subtle.decrypt({name:Dn,iv:Nn(fr.decode(r))},a,Nn(fr.decode(n)));return new TextDecoder().decode(i)}o(Gt,"decryptSecret");function hP(e,t){let r=pr({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-secret")throw g("invalid_request",`Upstream server ${e} does not use tenant static credentials.`);return r.secret}o(hP,"requireTenantStaticSecretConfig");function qh(e){return e?.status==="active"&&e.metadata?.staticSecretKind==="bearer_token"&&!!e.metadata.encryptedStaticSecret}o(qh,"hasUsableTenantStaticSecret");async function gP(e){if(!qh(e.connection))throw g("internal_server_error","Stored tenant static credential is incomplete.");return{type:"bearer_token",token:await Gt(e.connection.metadata.encryptedStaticSecret)}}o(gP,"resolveTenantStaticSecretCredential");async function Nh(e){let t=De(e.upstreamServerId);hP(e.upstreamServerId,e.authProfileId);let r="preloadedConnection"in e?e.preloadedConnection:(await K().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(qh(r))return{kind:"authorized",credential:await gP({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:$h(n)}}o(Nh,"resolveTenantStaticSecretCredentialForRequest");ae();async function Fu(e){return K().upsertUpstreamConnection({id:oi(),ownerMode:e.owner.mode,subjectId:e.owner.mode==="user"?e.owner.subjectId:void 0,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,status:"active",encryptedAccessToken:void 0,encryptedRefreshToken:void 0,scopes:[],expiresAt:void 0,metadata:e.metadata})}o(Fu,"upsertStaticSecretConnection");var yP=u.string().trim().min(1).max(320),SP=u.string().min(1).max(4096),vP=u.string().trim().min(1).max(4096);function Zu(e,t){let r=pr({upstreamServerId:e,authProfileId:t});if(r.mode!=="user-secret")throw g("invalid_request",`Upstream server ${e} does not use user static credentials.`);return r.secret}o(Zu,"requireUserStaticSecretConfig");function _P(e){let t=new TextEncoder().encode(e),r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}o(_P,"encodeBase64Utf8");function wP(e){return`Basic ${_P(`${e.username}:${e.appPassword}`)}`}o(wP,"buildBasicAuthHeader");function Dh(e){return e?.status==="active"&&!!e.metadata?.encryptedStaticSecret}o(Dh,"hasEncryptedUserStaticSecret");async function bP(e){if(!Dh(e.connection))throw g("internal_server_error","Stored user static credential is incomplete.");if(e.connection.metadata.staticSecretKind==="bearer_token")return{type:"bearer_token",token:await Gt(e.connection.metadata.encryptedStaticSecret)};if(e.connection.metadata.staticSecretKind==="basic_auth_app_password"&&e.connection.metadata.staticSecretUsername)return{type:"headers",headers:{Authorization:wP({username:e.connection.metadata.staticSecretUsername,appPassword:await Gt(e.connection.metadata.encryptedStaticSecret)})}};throw g("internal_server_error","Stored user static credential kind is unsupported.")}o(bP,"resolveUserStaticSecretCredential");async function jh(e){if(Zu(e.upstreamServerId,e.authProfileId).kind!=="basic_auth_app_password")throw g("invalid_request","This upstream does not use username and app-password credentials.");if(e.owner.mode!=="user")throw g("invalid_request","User static credentials must be stored under a user-owned connection.");let r=yP.parse(e.username),n=SP.parse(e.appPassword);return Fu({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await Br(n),staticSecretKind:"basic_auth_app_password",staticSecretUsername:r}})}o(jh,"saveUserStaticSecretCredential");async function zi(e){let t=Zu(e.upstreamServerId,e.authProfileId);if(t.kind!=="bearer_token")throw g("invalid_request","This upstream does not use bearer token credentials.");if(e.owner.mode!=="user")throw g("invalid_request","User static credentials must be stored under a user-owned connection.");let r=vP.parse(e.token);return Fu({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await Br(r),staticSecretKind:t.kind,staticSecretLabel:t.label}})}o(zi,"saveUserStaticBearerTokenCredential");function Ku(e,t){return Zu(e,t)}o(Ku,"readUserStaticSecretCaptureConfig");async function Hh(e){let t=De(e.upstreamServerId);if(e.owner.mode!=="user")throw g("internal_server_error","User static credential flow resolved a non-user owner.");let r="preloadedConnection"in e?e.preloadedConnection:(await K().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(Dh(r))return{kind:"authorized",credential:await bP({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 qn(n)}}o(Hh,"resolveUserStaticSecretCredentialForRequest");function Lh(e){if(e.owner.mode!=="user")throw g("invalid_request","User static credential capture requires a user-owned connection.");return Eh({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(Lh,"buildUserStaticSecretConnectUrl");var Ju;Ju=globalThis.crypto;async function RP(e){return(await Ju).getRandomValues(new Uint8Array(e))}o(RP,"getRandomValues");async function CP(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let a=await RP(e-n.length);for(let i of a)i<r&&(n+=t[i%t.length])}return n}o(CP,"random");async function IP(e){return await CP(e)}o(IP,"generateVerifier");async function PP(e){let t=await(await Ju).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(PP,"generateChallenge");async function Wu(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await IP(e),r=await PP(t);return{code_verifier:t,code_challenge:r}}o(Wu,"pkceChallenge");ae();var Ee=Yp().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:tm.custom,message:"URL must be parseable",fatal:!0}),Jp}).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"}),Mi=Ce({resource:f().url(),authorization_servers:C(Ee).optional(),jwks_uri:f().url().optional(),scopes_supported:C(f()).optional(),bearer_methods_supported:C(f()).optional(),resource_signing_alg_values_supported:C(f()).optional(),resource_name:f().optional(),resource_documentation:f().optional(),resource_policy_uri:f().url().optional(),resource_tos_uri:f().url().optional(),tls_client_certificate_bound_access_tokens:oe().optional(),authorization_details_types_supported:C(f()).optional(),dpop_signing_alg_values_supported:C(f()).optional(),dpop_bound_access_tokens_required:oe().optional()}),jo=Ce({issuer:f(),authorization_endpoint:Ee,token_endpoint:Ee,registration_endpoint:Ee.optional(),scopes_supported:C(f()).optional(),response_types_supported:C(f()),response_modes_supported:C(f()).optional(),grant_types_supported:C(f()).optional(),token_endpoint_auth_methods_supported:C(f()).optional(),token_endpoint_auth_signing_alg_values_supported:C(f()).optional(),service_documentation:Ee.optional(),revocation_endpoint:Ee.optional(),revocation_endpoint_auth_methods_supported:C(f()).optional(),revocation_endpoint_auth_signing_alg_values_supported:C(f()).optional(),introspection_endpoint:f().optional(),introspection_endpoint_auth_methods_supported:C(f()).optional(),introspection_endpoint_auth_signing_alg_values_supported:C(f()).optional(),code_challenge_methods_supported:C(f()).optional(),client_id_metadata_document_supported:oe().optional()}),xP=Ce({issuer:f(),authorization_endpoint:Ee,token_endpoint:Ee,userinfo_endpoint:Ee.optional(),jwks_uri:Ee,registration_endpoint:Ee.optional(),scopes_supported:C(f()).optional(),response_types_supported:C(f()),response_modes_supported:C(f()).optional(),grant_types_supported:C(f()).optional(),acr_values_supported:C(f()).optional(),subject_types_supported:C(f()),id_token_signing_alg_values_supported:C(f()),id_token_encryption_alg_values_supported:C(f()).optional(),id_token_encryption_enc_values_supported:C(f()).optional(),userinfo_signing_alg_values_supported:C(f()).optional(),userinfo_encryption_alg_values_supported:C(f()).optional(),userinfo_encryption_enc_values_supported:C(f()).optional(),request_object_signing_alg_values_supported:C(f()).optional(),request_object_encryption_alg_values_supported:C(f()).optional(),request_object_encryption_enc_values_supported:C(f()).optional(),token_endpoint_auth_methods_supported:C(f()).optional(),token_endpoint_auth_signing_alg_values_supported:C(f()).optional(),display_values_supported:C(f()).optional(),claim_types_supported:C(f()).optional(),claims_supported:C(f()).optional(),service_documentation:f().optional(),claims_locales_supported:C(f()).optional(),ui_locales_supported:C(f()).optional(),claims_parameter_supported:oe().optional(),request_parameter_supported:oe().optional(),request_uri_parameter_supported:oe().optional(),require_request_uri_registration:oe().optional(),op_policy_uri:Ee.optional(),op_tos_uri:Ee.optional(),client_id_metadata_document_supported:oe().optional()}),qi=I({...xP.shape,...jo.pick({code_challenge_methods_supported:!0}).shape}),Ho=I({access_token:f(),id_token:f().optional(),token_type:f(),expires_in:rm.number().optional(),scope:f().optional(),refresh_token:f().optional()}).strip(),Gh=I({error:f(),error_description:f().optional(),error_uri:f().optional()}),Bh=Ee.optional().or(U("").transform(()=>{})),kP=I({redirect_uris:C(Ee),token_endpoint_auth_method:f().optional(),grant_types:C(f()).optional(),response_types:C(f()).optional(),client_name:f().optional(),client_uri:Ee.optional(),logo_uri:Bh,scope:f().optional(),contacts:C(f()).optional(),tos_uri:Bh,policy_uri:f().optional(),jwks_uri:Ee.optional(),jwks:Xp().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional()}).strip(),Yu=I({client_id:f(),client_secret:f().optional(),client_id_issued_at:X().optional(),client_secret_expires_at:X().optional()}).strip(),Lo=kP.merge(Yu),TH=I({error:f(),error_description:f().optional()}).strip(),AH=I({token:f(),token_type_hint:f().optional()}).strip();function Vh(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(Vh,"resourceUrlFromServerUrl");function Fh({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(Fh,"checkResourceAllowed");var be=class extends Error{static{o(this,"OAuthError")}constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},Bo=class extends be{static{o(this,"InvalidRequestError")}};Bo.errorCode="invalid_request";var Gr=class extends be{static{o(this,"InvalidClientError")}};Gr.errorCode="invalid_client";var Vr=class extends be{static{o(this,"InvalidGrantError")}};Vr.errorCode="invalid_grant";var Fr=class extends be{static{o(this,"UnauthorizedClientError")}};Fr.errorCode="unauthorized_client";var Go=class extends be{static{o(this,"UnsupportedGrantTypeError")}};Go.errorCode="unsupported_grant_type";var Vo=class extends be{static{o(this,"InvalidScopeError")}};Vo.errorCode="invalid_scope";var Fo=class extends be{static{o(this,"AccessDeniedError")}};Fo.errorCode="access_denied";var Vt=class extends be{static{o(this,"ServerError")}};Vt.errorCode="server_error";var Zo=class extends be{static{o(this,"TemporarilyUnavailableError")}};Zo.errorCode="temporarily_unavailable";var Ko=class extends be{static{o(this,"UnsupportedResponseTypeError")}};Ko.errorCode="unsupported_response_type";var Jo=class extends be{static{o(this,"UnsupportedTokenTypeError")}};Jo.errorCode="unsupported_token_type";var Wo=class extends be{static{o(this,"InvalidTokenError")}};Wo.errorCode="invalid_token";var Yo=class extends be{static{o(this,"MethodNotAllowedError")}};Yo.errorCode="method_not_allowed";var Qo=class extends be{static{o(this,"TooManyRequestsError")}};Qo.errorCode="too_many_requests";var Zr=class extends be{static{o(this,"InvalidClientMetadataError")}};Zr.errorCode="invalid_client_metadata";var Xo=class extends be{static{o(this,"InsufficientScopeError")}};Xo.errorCode="insufficient_scope";var ea=class extends be{static{o(this,"InvalidTargetError")}};ea.errorCode="invalid_target";var Zh={[Bo.errorCode]:Bo,[Gr.errorCode]:Gr,[Vr.errorCode]:Vr,[Fr.errorCode]:Fr,[Go.errorCode]:Go,[Vo.errorCode]:Vo,[Fo.errorCode]:Fo,[Vt.errorCode]:Vt,[Zo.errorCode]:Zo,[Ko.errorCode]:Ko,[Jo.errorCode]:Jo,[Wo.errorCode]:Wo,[Yo.errorCode]:Yo,[Qo.errorCode]:Qo,[Zr.errorCode]:Zr,[Xo.errorCode]:Xo,[ea.errorCode]:ea};var Ft=class extends Error{static{o(this,"UnauthorizedError")}constructor(t){super(t??"Unauthorized")}};function TP(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(TP,"isClientAuthMethod");var Qu="code",Xu="S256";function AP(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&TP(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(AP,"selectClientAuthMethod");function EP(e,t,r,n){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":UP(a,i,r);return;case"client_secret_post":OP(a,i,n);return;case"none":$P(a,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(EP,"applyClientAuthentication");function UP(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(UP,"applyBasicAuth");function OP(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(OP,"applyPostAuth");function $P(e,t){t.set("client_id",e)}o($P,"applyPublicAuth");async function Jh(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=Gh.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:s}=n,c=Zh[a]||Vt;return new c(i||"",s)}catch(n){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Vt(a)}}o(Jh,"parseErrorResponse");async function hr(e,t){try{return await ed(e,t)}catch(r){if(r instanceof Gr||r instanceof Fr)return await e.invalidateCredentials?.("all"),await ed(e,t);if(r instanceof Vr)return await e.invalidateCredentials?.("tokens"),await ed(e,t);throw r}}o(hr,"auth");async function ed(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:a,fetchFn:i}){let s=await e.discoveryState?.(),c,d,p,l=a;if(!l&&s?.resourceMetadataUrl&&(l=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(d=s.authorizationServerUrl,c=s.resourceMetadata,p=s.authorizationServerMetadata??await Yh(d,{fetchFn:i}),!c)try{c=await Wh(t,{resourceMetadataUrl:l},i)}catch{}(p!==s.authorizationServerMetadata||c!==s.resourceMetadata)&&await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}else{let R=await jP(t,{resourceMetadataUrl:l,fetchFn:i});d=R.authorizationServerUrl,p=R.authorizationServerMetadata,c=R.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}let m=await zP(t,e,c),h=n||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,y=await Promise.resolve(e.clientInformation());if(!y){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let R=p?.client_id_metadata_document_supported===!0,z=e.clientMetadataUrl;if(z&&!rd(z))throw new Zr(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${z}`);if(R&&z)y={client_id:z},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let Me=await VP(d,{metadata:p,clientMetadata:e.clientMetadata,scope:h,fetchFn:i});await e.saveClientInformation(Me),y=Me}}let v=!e.redirectUrl;if(r!==void 0||v){let R=await GP(e,d,{metadata:p,resource:m,authorizationCode:r,fetchFn:i});return await e.saveTokens(R),"AUTHORIZED"}let S=await e.tokens();if(S?.refresh_token)try{let R=await BP(d,{metadata:p,clientInformation:y,refreshToken:S.refresh_token,resource:m,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(R),"AUTHORIZED"}catch(R){if(!(!(R instanceof be)||R instanceof Vt))throw R}let _=e.state?await e.state():void 0,{authorizationUrl:w,codeVerifier:b}=await HP(d,{metadata:p,clientInformation:y,state:_,redirectUrl:e.redirectUrl,scope:h,resource:m});return await e.saveCodeVerifier(b),await e.redirectToAuthorization(w),"REDIRECT"}o(ed,"authInternal");function rd(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(rd,"isHttpsUrl");async function zP(e,t,r){let n=Vh(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!Fh({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(zP,"selectResourceURL");function nd(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let a=td(e,"resource_metadata")||void 0,i;if(a)try{i=new URL(a)}catch{}let s=td(e,"scope")||void 0,c=td(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:c}}o(nd,"extractWWWAuthenticateParams");function td(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),a=r.match(n);return a?a[1]||a[2]:null}o(td,"extractFieldFromWwwAuth");async function Wh(e,t,r=fetch){let n=await NP(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 Mi.parse(await n.json())}o(Wh,"discoverOAuthProtectedResourceMetadata");async function od(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?od(e,void 0,r):void 0;throw n}}o(od,"fetchWithCorsRetry");function MP(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(MP,"buildWellKnownPath");async function Kh(e,t,r=fetch){return await od(e,{"MCP-Protocol-Version":t},r)}o(Kh,"tryMetadataDiscovery");function qP(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}o(qP,"shouldAttemptFallback");async function NP(e,t,r,n){let a=new URL(e),i=n?.protocolVersion??sr,s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{let d=MP(t,a.pathname);s=new URL(d,n?.metadataServerUrl??a),s.search=a.search}let c=await Kh(s,i,r);if(!n?.metadataUrl&&qP(c,a.pathname)){let d=new URL(`/.well-known/${t}`,a);c=await Kh(d,i,r)}return c}o(NP,"discoverMetadataWithFallback");function DP(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(DP,"buildDiscoveryUrls");async function Yh(e,{fetchFn:t=fetch,protocolVersion:r=sr}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},a=DP(e);for(let{url:i,type:s}of a){let c=await od(i,n,t);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return s==="oauth"?jo.parse(await c.json()):qi.parse(await c.json())}}}o(Yh,"discoverAuthorizationServerMetadata");async function jP(e,t){let r,n;try{r=await Wh(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 Yh(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:a,resourceMetadata:r}}o(jP,"discoverOAuthServerInfo");async function HP(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:a,state:i,resource:s}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Qu))throw new Error(`Incompatible auth server: does not support response type ${Qu}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Xu))throw new Error(`Incompatible auth server: does not support code challenge method ${Xu}`)}else c=new URL("/authorize",e);let d=await Wu(),p=d.code_verifier,l=d.code_challenge;return c.searchParams.set("response_type",Qu),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",l),c.searchParams.set("code_challenge_method",Xu),c.searchParams.set("redirect_uri",String(n)),i&&c.searchParams.set("state",i),a&&c.searchParams.set("scope",a),a?.includes("offline_access")&&c.searchParams.append("prompt","consent"),s&&c.searchParams.set("resource",s.href),{authorizationUrl:c,codeVerifier:p}}o(HP,"startAuthorization");function LP(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(LP,"prepareAuthorizationCodeRequest");async function Qh(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=AP(n,l);EP(m,n,d,r)}let p=await(s??fetch)(c,{method:"POST",headers:d,body:r});if(!p.ok)throw await Jh(p);return Ho.parse(await p.json())}o(Qh,"executeTokenRequest");async function BP(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 Qh(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:s});return{refresh_token:n,...d}}o(BP,"refreshAuthorization");async function GP(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=LP(a,p,e.redirectUrl)}let d=await e.clientInformation();return Qh(t,{metadata:r,tokenRequestParams:c,clientInformation:d??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:i})}o(GP,"fetchToken");async function VP(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 Jh(s);return Lo.parse(await s.json())}o(VP,"registerClient");ae();function ad(e){return`Zuplo MCP Gateway - ${e}`}o(ad,"buildGatewayOAuthClientName");function Xh(e,t){let r=new URL(e,ie(t));return qe(r)&&Nt(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}o(Xh,"buildGatewayOAuthRedirectUri");function id(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}o(id,"buildOAuthClientMetadataDocumentUrl");function eg(e){return ie(e)}o(eg,"requireOAuthClientMetadataOrigin");function tg(e,t,r){let n=De(t),a=Lr(t,r);return{client_id:id({origin:e,upstreamServerId:t,authProfileId:r}),client_name:ad(n.displayName),client_uri:new URL("/",e).toString(),redirect_uris:[new URL(a.redirectPath,e).toString()],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",token_endpoint_auth_method:"none"}}o(tg,"buildOAuthClientMetadataDocument");var FP=u.union([Lo,Yu]),ZP=u.object({authorizationServerUrl:u.url(),resourceMetadataUrl:u.url().optional(),resourceMetadata:Mi.optional(),authorizationServerMetadata:u.union([jo,qi]).optional()}).passthrough(),KP="Bearer";function JP(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o(JP,"splitScopes");function WP(e){return Wa.parse(e)}o(WP,"parsePkceCodeVerifier");function YP(e){if(typeof e.expires_in=="number")return re(new Date(Date.now()+e.expires_in*1e3))}o(YP,"readTokenExpiry");async function rg(e){if(e!==void 0)return Br(JSON.stringify(e))}o(rg,"encryptJson");async function ng(e,t){if(!e)return;let r=await Gt(e);try{return t.parse(JSON.parse(r))}catch(n){throw g("oauth_state_invalid","Stored upstream OAuth JSON state is invalid.",n)}}o(ng,"decryptJson");function QP(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(QP,"toOAuthDiscoveryState");function XP(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(XP,"clientInformationAllowsRedirectUri");function ex(e,t,r){let n=De(e),a=Lr(e,t),i;return a.scopes.length>0&&(i=a.scopes.join(a.scopeDelimiter)),{client_name:ad(n.displayName),client_uri:new URL("/",new URL(r).origin).toString(),redirect_uris:[r],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",scope:i,token_endpoint_auth_method:"none"}}o(ex,"buildOAuthClientMetadata");function tx(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw g("internal_server_error",`Manual OAuth registration for ${e.upstreamServerId} requires clientSecret.`);return Lo.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(tx,"buildManualOAuthClientInformation");function rx(e,t,r){let n=id({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return rd(n)?n:void 0}o(rx,"buildClientMetadataUrl");function og(e){for(let t of e)if(t!==void 0)return t}o(og,"firstDefined");function nx(e){let t=Lr(e.target.upstreamServerId,e.target.authProfileId),r=ex(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredClientInformation:tx({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let n=rx(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return n===void 0?{clientMetadata:r}:{clientMetadata:r,clientMetadataUrl:n}}o(nx,"buildInitialOAuthClientSetup");function ox(e,t){if(t===void 0)return og([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(ox,"readEncryptedClientInformation");function ax(e){return og([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}o(ax,"readEncryptedDiscoveryState");var Kr=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=nx({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=ox(t,this.configuredClientInformation),this.encryptedDiscoveryState=ax(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return this.clientMetadataValue}async state(){let t=await this.createPendingState();return kh({id:t.id,...Io({owner:this.target.owner,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId})})}async clientInformation(){return this.configuredClientInformation?this.configuredClientInformation:this.loadPersistedClientInformation()}async saveClientInformation(t){this.configuredClientInformation||(this.cachedClientInformation=t,this.clientInformationLoaded=!0,this.encryptedClientInformation=await rg(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await rg(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Ho.parse(t),n=this.target.owner.mode==="user"?this.target.owner.subjectId:void 0;this.cachedTokens=r,this.tokensLoaded=!0;let a={id:this.connection?.id??oi(),ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Br(r.access_token),encryptedRefreshToken:r.refresh_token?await Br(r.refresh_token):void 0,scopes:JP(r.scope??this.clientMetadataValue.scope),expiresAt:YP(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await K().upsertUpstreamConnection(a)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:WP(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw g("oauth_state_invalid","OAuth code verifier is missing");return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",n=t==="all"||t==="client",a=t==="all"||t==="discovery",i=t==="all"||t==="verifier";n&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),a&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:$m(),...Io({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,virtualServerId:this.target.virtualServerId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:re(new Date(Date.now()+Ih)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await K().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await ng(this.encryptedClientInformation,FP)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!XP(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=QP(await ng(this.encryptedDiscoveryState,ZP))}catch{this.encryptedDiscoveryState=void 0,this.cachedDiscoveryState=void 0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1)}return this.discoveryStateLoaded=!0,this.cachedDiscoveryState}async loadStoredTokens(){if(this.tokensLoaded)return this.cachedTokens;if(this.tokensLoaded=!0,!this.connection?.encryptedAccessToken||this.connection.status!=="active")return;let t=Ho.parse({access_token:await Gt(this.connection.encryptedAccessToken),token_type:KP,refresh_token:this.connection.encryptedRefreshToken?await Gt(this.connection.encryptedRefreshToken):void 0,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=t,t}async persistCredentialInvalidation(t){if(!this.connection)return;let r={id:this.connection.id,ownerMode:this.connection.ownerMode,subjectId:this.connection.subjectId,upstreamServerId:this.connection.upstreamServerId,authProfileId:this.connection.authProfileId,status:this.connection.status,encryptedAccessToken:this.connection.encryptedAccessToken,encryptedRefreshToken:this.connection.encryptedRefreshToken,scopes:[...this.connection.scopes],expiresAt:this.connection.expiresAt,metadata:this.connection.metadata?{...this.connection.metadata}:void 0};t&&(r.status="reconsent_required",r.encryptedAccessToken=void 0,r.encryptedRefreshToken=void 0,r.scopes=[],r.expiresAt=void 0),r.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await K().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var ix=1e4,sx=256*1024,cx=2;function ux(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}o(ux,"hasUsableAccessToken");var dx="does not support dynamic client registration";function lx(e){return e instanceof Error&&e.message.includes(dx)}o(lx,"isDynamicClientRegistrationUnsupported");function px(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o(px,"readOAuthFetchRequest");function mx(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(mx,"responseLooksJson");function ag(e){return async(t,r)=>{let n=px(t),a=await Mn(t,r,{maxRedirects:cx,maxResponseBytes:sx,problemCode:"upstream_token_exchange_failed",timeoutMs:ix}),i=await a.clone().text();if(!mx(a,i))return a;try{JSON.parse(i)}catch(s){throw g("upstream_token_exchange_failed",`Upstream OAuth fetch ${n.url.origin}${n.url.pathname} for ${e} returned invalid JSON.`,s)}return a}}o(ag,"createUpstreamOAuthFetch");async function ig(e,t){try{return await hr(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:ag(t.upstreamServerId)})}catch(r){throw lx(r)?g("upstream_client_registration_required",`The authorization server for ${t.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register a client for the gateway manually before retrying.`,r):r}}o(ig,"runUpstreamOAuth");async function fx(e,t){return hr(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:ag(t.upstreamServerId)})}o(fx,"exchangeUpstreamAuthorizationCode");async function sg(e,t){let r=await ig(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?g("upstream_token_exchange_failed",`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`):g("upstream_token_exchange_failed",`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`)}o(sg,"requireUpstreamAuthorizationRedirect");async function cg(e){if(ux(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await ig(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl});if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw g("upstream_token_exchange_failed",`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`);if(!e.provider.authorizationUrl)throw g("upstream_token_exchange_failed",`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`);return{kind:"connect_required",payload:await vx({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(cg,"authorizeUpstreamOAuthSession");async function hx(e){let t=await Ui(e.stateToken),r=await K().consumeUpstreamOAuthState({id:t.id,now:re(new Date)}),n=gx(r);return yx({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Sx(n),n}o(hx,"consumeStoredCallbackState");function gx(e){switch(e.kind){case"consumed":throw g("oauth_state_reused","OAuth state has already been used");case"missing":throw g("oauth_state_expired","OAuth state is missing or expired");case"available":return e.record}}o(gx,"readConsumedCallbackState");function yx(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.virtualServerId===e.signedState.virtualServerId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw g("oauth_callback_mismatch","OAuth callback did not match the initiating request")}o(yx,"assertStoredCallbackStateMatches");function Sx(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw g("oauth_state_expired","OAuth state has expired")}o(Sx,"assertStoredCallbackStateFresh");async function vx(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),Uh(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),qn(t)}o(vx,"buildOAuthConnectRequiredResponse");async function ug(e){let t=await hx({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=Pn(t),[n]=await K().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),a={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};n!==void 0&&(a.connection=n);let i=new Kr(a),s=await fx(i,{upstreamServerId:e.upstreamServerId,serverUrl:e.upstreamServerConfig.transport.baseUrl,authorizationCode:e.authorizationCode,resourceMetadataUrl:e.upstreamServerConfig.transport.resourceMetadataUrl});if(s==="AUTHORIZED")return t;throw s!=="REDIRECT"?g("upstream_token_exchange_failed",`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`):g("upstream_token_exchange_failed",`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`)}o(ug,"finishUpstreamOAuthCallback");async function dg(e){let t=De(e.upstreamServerId),r=Lr(e.upstreamServerId,e.authProfileId),n=Xh(r.redirectPath,e.request.url),a="preloadedConnection"in e?e.preloadedConnection:(await K().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:a,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}},redirectUri:n,returnOrigin:ie(e.request.url)}}}o(dg,"prepareUpstreamOAuthRequest");async function lg(e){let t=await dg(e),r=new Kr({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return sg(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(lg,"startUpstreamConnect");async function pg(e){let t=await dg(e),r=new Kr({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return cg({target:e,provider:r,connection:t.connection,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(pg,"authorizeUpstreamRequest");function _x(e,t){switch(e.kind){case"bearer_token":{if(!e.token)throw g("internal_server_error",`Static bearer token is not configured for upstream ${t}.`);return{type:"bearer_token",token:e.token}}case"headers":{let r={};for(let n of e.headers){if(!n.value)throw g("internal_server_error",`Static header ${n.name} is not configured for upstream ${t}.`);r[n.name]=n.value}return{type:"headers",headers:r}}}}o(_x,"resolveStaticSecretCredential");async function Ni(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return pg({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 Nh({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=pr({upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId});if(n.mode!=="static-secret")throw g("internal_server_error",`Resolved static-secret credential context loaded ${n.mode} config.`);return{kind:"authorized",credential:_x(n.secret,t.upstreamServerId)}}case"user-secret":return Hh({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,authProfileId:t.authProfileId,upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}})}throw g("internal_server_error",`Unsupported upstream auth route context ${JSON.stringify(t)}.`)}o(Ni,"resolveUpstreamCredentialForRoute");async function mg(e){let t=ir(e.principal.subjectId),r=yt().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 zi({owner:t,initiatedBySubjectId:e.principal.subjectId,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId,token:e.apiKey})}o(mg,"saveBrowserLoginApiKeyCredentialsForVirtualServer");async function fg(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=Pt(e.connectRequest.authMode);switch(n.connectSupport){case"oauth_authorization":t=await lg(r);break;case"user_secret_capture":t=await Lh(r);break;case"none":throw g("invalid_request",n.connectUnsupportedDetail??`Upstream server ${e.connectRequest.upstreamServerId} does not support browser connection flows.`)}return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,virtualServerId:e.connectRequest.virtualServerId}}o(fg,"startUpstreamConnectForRequest");async function hg(e){let r=(await Ui(e.callbackRequest.state)).authProfileId,n=pr({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if(Pt(n.mode).callbackSupport!=="authorization_code")throw g("invalid_request",`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:De(e.callbackRequest.upstreamServerId)})}o(hg,"finishUpstreamCallbackForRequest");var sd=new Ct("route-upstream-bindings");function gg(e){return`${e.upstreamServerId}:${e.authProfileId}`}o(gg,"buildRouteBindingDuplicateKey");function cd(e,t){let r=sd.get(e)??[],n=gg(t);if(r.find(i=>gg(i)===n)!==void 0)throw g("internal_server_error",`Route declares duplicate upstream binding ${t.upstreamServerId} + ${t.authProfileId}.`);r.push(t),sd.set(e,r)}o(cd,"appendResolvedUpstreamBindingContext");function Di(e){return sd.get(e)??[]}o(Di,"readResolvedUpstreamBindingContexts");var wx=new Set(["authorization","connection","content-length","cookie","cookie2","host","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),bx=3e4,Rx=2*1024*1024,Cx=2;function Ix(e){return e.kind!=="authorized"||e.credential.type!=="headers"?[]:Object.keys(e.credential.headers)}o(Ix,"readCredentialHeaderNames");async function Px(e,t){Rt("handler.mcp-upstream");let r=Di(t);if(r.length!==1)throw new ue(`mcpUpstreamHandler requires exactly one upstream binding on the route (found ${r.length}). Attach a single \`mcp-upstream-connection-inbound\` policy or use \`McpVirtualServerHandler\` for multi-upstream routes.`);let[n]=r,a=await Ni({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=De(n.upstreamServerId),s=i.transport.baseUrl,c=new Headers;for(let[h,y]of e.headers.entries())wx.has(h.toLowerCase())||c.set(h,y);let d=[];for(let h of i.transport.requestHeaders??[]){if(h.value===void 0){if(h.required)throw new ue(`mcpUpstreamHandler: configured request header '${h.name}' is required but its value is unset. Set the env var that backs the header or mark the header optional.`);continue}c.set(h.name,h.value),d.push(h.name)}let p=a.credential;switch(p.type){case"bearer_token":c.set("authorization",`Bearer ${p.token}`);break;case"headers":for(let[h,y]of Object.entries(p.headers))c.set(h,y);break;case"mcp_oauth_provider":{let h=await p.provider.tokens();if(!h)return t.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:n.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),Response.json({error:"no_upstream_tokens"},{status:401});c.set("authorization",`${h.token_type??"Bearer"} ${h.access_token}`);break}}let l=[...d,...Ix(a)],m={method:e.method,headers:c,body:e.method==="GET"||e.method==="HEAD"?void 0:e.body,duplex:"half"};return t.log.info({event:"mcp_upstream_handler_proxy",upstreamServerId:n.upstreamServerId,upstreamUrl:s,method:e.method},"MCP upstream proxy: forwarding request"),Mn(s,m,{additionalCrossOriginStrippedHeaders:l,context:t,maxRedirects:Cx,maxResponseBytes:Rx,problemCode:"upstream_capability_invocation_failed",timeoutMs:bx})}o(Px,"mcpUpstreamHandler");Iw();function gr(e){return!!e._zod}o(gr,"isZ4Schema");function Ge(e,t){return gr(e)?dc(e,t):e.safeParse(t)}o(Ge,"safeParse");function jn(e){if(!e)return;let t;if(gr(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 yg(e){if(gr(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(yg,"getLiteralValue");function yr(e){return e==="completed"||e==="failed"||e==="cancelled"}o(yr,"isTerminal");var kx=Symbol("Let zodToJsonSchema decide on which parser to use");var t2=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ud(e){let r=jn(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=yg(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}o(ud,"getMethodLiteral");function dd(e,t){let r=Ge(e,t);if(!r.success)throw r.error;return r.data}o(dd,"parseWithCompat");var $x=6e4,Hn=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(di,r=>{this._oncancel(r)}),this.setNotificationHandler(fi,r=>{this._onprogress(r)}),this.setRequestHandler(mi,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(hi,async(r,n)=>{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new x(E.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(yi,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 x(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 x(E.InvalidParams,`Task not found: ${i}`);if(!yr(s.status))return await this._waitForTaskUpdate(i,n.signal),await a();if(yr(s.status)){let c=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...c,_meta:{...c._meta,[ur]:{taskId:i}}}}return await a()},"handleTaskResult");return await a()}),this.setRequestHandler(Si,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 x(E.InvalidParams,`Failed to list tasks: ${a instanceof Error?a.message:String(a)}`)}}),this.setRequestHandler(_i,async(r,n)=>{try{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new x(E.InvalidParams,`Task not found: ${r.params.taskId}`);if(yr(a.status))throw new x(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 x(E.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(a){throw a instanceof x?a:new x(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),x.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),gt(i)||En(i)?this._onresponse(i):It(i)?this._onrequest(i,s):qf(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=x.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?.[ur]?.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=$f(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 x(E.ConnectionClosed,"Request was cancelled");let y={...h,relatedRequestId:t.id};i&&!y.relatedTask&&(y.relatedTask={taskId:i});let v=y.relatedTask?.taskId??i;return v&&d&&await d.updateTaskStatus(v,"input_required"),await this.request(l,m,y)},"sendRequest"),authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:c?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{c&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,p)).then(async l=>{if(s.signal.aborted)return;let m={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:m,timestamp:Date.now()},a?.sessionId):await a?.send(m)},async l=>{if(s.signal.aborted)return;let m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:E.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"error",message:m,timestamp:Date.now()},a?.sessionId):await a?.send(m)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(t.id)===s&&this._requestHandlerAbortControllers.delete(t.id)})}_onprogress(t){let{progressToken:r,...n}=t.params,a=Number(r),i=this._progressHandlers.get(a);if(!i){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(t)}`));return}let s=this._responseHandlers.get(a),c=this._timeoutInfo.get(a);if(c&&s&&c.resetTimeoutOnProgress)try{this._resetTimeout(a)}catch(d){this._responseHandlers.delete(a),this._progressHandlers.delete(a),this._cleanupTimeout(a),s(d);return}i(n)}_onresponse(t){let r=Number(t.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),gt(t))n(t);else{let s=new x(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(gt(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),gt(t))a(t);else{let s=x.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 x?s:new x(E.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Bt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new x(E.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:c},yr(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:c.status==="failed"?yield{type:"error",error:new x(E.InternalError,`Task ${i} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new x(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 x?s:new x(E.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s,task:c,relatedTask:d}=n??{};return new Promise((p,l)=>{let m=o(b=>{l(b)},"earlyReject");if(!this._transport){m(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),c&&this.assertTaskCapability(t.method)}catch(b){m(b);return}n?.signal?.throwIfAborted();let h=this._requestMessageId++,y={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),y.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),c&&(y.params={...y.params,task:c}),d&&(y.params={...y.params,_meta:{...y.params?._meta||{},[ur]:d}});let v=o(b=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(b)}},{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(z=>this._onerror(new Error(`Failed to send cancellation: ${z}`)));let R=b instanceof x?b:new x(E.RequestTimeout,String(b));l(R)},"cancel");this._responseHandlers.set(h,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return l(b);try{let R=Ge(r,b.result);R.success?p(R.data):l(R.error)}catch(R){l(R)}}}),n?.signal?.addEventListener("abort",()=>{v(n?.signal?.reason)});let S=n?.timeout??$x,_=o(()=>v(x.fromError(E.RequestTimeout,"Request timed out",{timeout:S})),"timeoutHandler");this._setupTimeout(h,S,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let w=d?.taskId;if(w){let b=o(R=>{let z=this._responseHandlers.get(h);z?z(R):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))},"responseResolver");this._requestResolvers.set(h,b),this._enqueueTaskMessage(w,{type:"request",message:y,timestamp:Date.now()}).catch(R=>{this._cleanupTimeout(h),l(R)})}else this._transport.send(y,{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(b=>{this._cleanupTimeout(h),l(b)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},gi,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},vi,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Df,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||{},[ur]: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||{},[ur]: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||{},[ur]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=ud(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(a,i)=>{let s=dd(t,a);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=ud(t);this._notificationHandlers.set(n,a=>{let i=dd(t,a);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let a=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,a)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let a of n)if(a.type==="request"&&It(a.message)){let i=a.message.id,s=this._requestResolvers.get(i);s?(s(new x(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 x(E.InvalidRequest,"Request cancelled"));return}let s=setTimeout(a,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new x(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 x(E.InvalidParams,"Failed to retrieve task: Task not found");return i},"getTask"),storeTaskResult:o(async(a,i,s)=>{await n.storeTaskResult(a,i,s,r);let c=await n.getTask(a,r);if(c){let d=$o.parse({method:"notifications/tasks/status",params:c});await this.notification(d),yr(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 x(E.InvalidParams,`Task "${a}" not found - it may have been cleaned up`);if(yr(c.status))throw new x(E.InvalidParams,`Cannot update task "${a}" from terminal status "${c.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(a,i,s,r);let d=await n.getTask(a,r);if(d){let p=$o.parse({method:"notifications/tasks/status",params:d});await this.notification(p),yr(d.status)&&this._cleanupTaskProgressHandler(a)}},"updateTaskStatus"),listTasks:o(a=>n.listTasks(a,r),"listTasks")}}};function Sg(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}o(Sg,"isPlainObject");function ji(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];Sg(s)&&Sg(i)?r[a]={...s,...i}:r[a]=i}return r}o(ji,"mergeCapabilities");var ov=Fp(Jl(),1),av=Fp(nv(),1);function CU(){let e=new ov.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,av.default)(e),e}o(CU,"createDefaultAjvInstance");var oo=class{static{o(this,"AjvJsonSchemaValidator")}constructor(t){this._ajv=t??CU()}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 Rs=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},jr,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},lr,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 Cs(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(Cs,"assertToolsCallTaskCapability");function Is(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(Is,"assertClientRequestTaskCapability");var Ps=class extends Hn{static{o(this,"Server")}constructor(t,r){super(r),this._serverInfo=t,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(qo.options.map((n,a)=>[n,a])),this.isMessageIgnored=(n,a)=>{let i=this._loggingLevels.get(a);return i?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(i):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new oo,this.setRequestHandler(li,n=>this._oninitialize(n)),this.setNotificationHandler(pi,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Ru,async(n,a)=>{let i=a.sessionId||a.requestInfo?.headers["mcp-session-id"]||void 0,{level:s}=n.params,c=qo.safeParse(s);return c.success&&this._loggingLevels.set(i,c.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Rs(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ji(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(gr(a)){let c=a;i=c._zod?.def?.value??c.value}else{let c=a;i=c._def?.value??c.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let c=o(async(d,p)=>{let l=Ge(Mo,d);if(!l.success){let v=l.error instanceof Error?l.error.message:String(l.error);throw new x(E.InvalidParams,`Invalid tools/call request: ${v}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let v=Ge(Bt,h);if(!v.success){let S=v.error instanceof Error?v.error.message:String(v.error);throw new x(E.InvalidParams,`Invalid task creation result: ${S}`)}return v.data}let y=Ge(dr,h);if(!y.success){let v=y.error instanceof Error?y.error.message:String(y.error);throw new x(E.InvalidParams,`Invalid tools/call result: ${v}`)}return y.data},"wrappedHandler");return super.setRequestHandler(t,c)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){Is(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&Cs(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:cr.includes(r)?r:sr,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},Lt)}async createMessage(t,r){if((t.tools||t.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(t.messages.length>0){let n=t.messages[t.messages.length-1],a=Array.isArray(n.content)?n.content:[n.content],i=a.some(p=>p.type==="tool_result"),s=t.messages.length>1?t.messages[t.messages.length-2]:void 0,c=s?Array.isArray(s.content)?s.content:[s.content]:[],d=c.some(p=>p.type==="tool_use");if(i){if(a.some(p=>p.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!d)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(d){let p=new Set(c.filter(m=>m.type==="tool_use").map(m=>m.id)),l=new Set(a.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(p.size!==l.size||![...p].every(m=>l.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return t.tools?this.request({method:"sampling/createMessage",params:t},No,r):this.request({method:"sampling/createMessage",params:t},jr,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},lr,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},lr,r);if(i.action==="accept"&&i.content&&a.requestedSchema)try{let c=this._jsonSchemaValidator.getValidator(a.requestedSchema)(i.content);if(!c.valid)throw new x(E.InvalidParams,`Elicitation response content does not match requested schema: ${c.errorMessage}`)}catch(s){throw s instanceof x?s:new x(E.InternalError,`Error validating elicitation response: ${s instanceof Error?s.message:String(s)}`)}return i}}}createElicitationCompletionNotifier(t,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:t}},r)}async listRoots(t,r){return this.request({method:"roots/list",params:t},xu,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var xs=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 aE={keyword:"dependencies",type:"object",schemaType:"object",error:Mt.error,code(e){let[t,r]=iE(e);RS(e,t),CS(e,r)}};function iE({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(iE,"splitDependencies");function RS(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,Ea.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,Ea.checkReportMissingProp)(e,p)}):(r.if((0,Tl._)`${d} && (${(0,Ea.checkMissingProp)(e,c,i)})`),(0,Ea.reportMissingProp)(e,i),r.else())}}o(RS,"validatePropertyDeps");Mt.validatePropertyDeps=RS;function CS(e,t=e.schema){let{gen:r,data:n,keyword:a,it:i}=e,s=r.name("valid");for(let c in t)(0,oE.alwaysValidSchema)(i,t[c])||(r.if((0,Ea.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(CS,"validateSchemaDeps");Mt.validateSchemaDeps=CS;Mt.default=aE});var xS=k(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});var PS=F(),sE=te(),cE={message:"property name must be valid",params:o(({params:e})=>(0,PS._)`{propertyName: ${e.propertyName}}`,"params")},uE={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:cE,code(e){let{gen:t,schema:r,data:n,it:a}=e;if((0,sE.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,PS.not)(i),()=>{e.error(!0),a.allErrors||t.break()})}),e.ok(i)}};Al.default=uE});var Ul=k(El=>{"use strict";Object.defineProperty(El,"__esModule",{value:!0});var Ss=gt(),It=F(),dE=Xt(),vs=te(),lE={message:"must NOT have additional properties",params:o(({params:e})=>(0,It._)`{additionalProperty: ${e.additionalProperty}}`,"params")},pE={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:lE,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,vs.alwaysValidSchema)(s,r))return;let p=(0,Ss.allSchemaProperties)(n.properties),l=(0,Ss.allSchemaProperties)(n.patternProperties);m(),e.ok((0,It._)`${i} === ${dE.default.errors}`);function m(){t.forIn("key",a,_=>{!p.length&&!l.length?v(_):t.if(h(_),()=>v(_))})}o(m,"checkAdditionalProperties");function h(_){let w;if(p.length>8){let b=(0,vs.schemaRefOrVal)(s,n.properties,"properties");w=(0,Ss.isOwnProperty)(t,b,_)}else p.length?w=(0,It.or)(...p.map(b=>(0,It._)`${_} === ${b}`)):w=It.nil;return l.length&&(w=(0,It.or)(w,...l.map(b=>(0,It._)`${(0,Ss.usePattern)(e,b)}.test(${_})`))),(0,It.not)(w)}o(h,"isAdditional");function y(_){t.code((0,It._)`delete ${a}[${_}]`)}o(y,"deleteAdditional");function v(_){if(d.removeAdditional==="all"||d.removeAdditional&&r===!1){y(_);return}if(r===!1){e.setParams({additionalProperty:_}),e.error(),c||t.break();return}if(typeof r=="object"&&!(0,vs.alwaysValidSchema)(s,r)){let w=t.name("valid");d.removeAdditional==="failing"?(S(_,w,!1),t.if((0,It.not)(w),()=>{e.reset(),y(_)})):(S(_,w),c||t.if((0,It.not)(w),()=>t.break()))}}o(v,"additionalPropertyCode");function S(_,w,b){let R={keyword:"additionalProperties",dataProp:_,dataPropType:vs.Type.Str};b===!1&&Object.assign(R,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(R,w)}o(S,"applyAdditionalSchema")}};El.default=pE});var AS=k($l=>{"use strict";Object.defineProperty($l,"__esModule",{value:!0});var mE=ya(),kS=gt(),Ol=te(),TS=Ul(),fE={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&&TS.default.code(new mE.KeywordCxt(i,TS.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=Ol.mergeEvaluated.props(t,(0,Ol.toHash)(s),i.props));let c=s.filter(m=>!(0,Ol.alwaysValidSchema)(i,r[m]));if(c.length===0)return;let d=t.name("valid");for(let m of c)p(m)?l(m):(t.if((0,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")}};$l.default=fE});var $S=k(Ml=>{"use strict";Object.defineProperty(Ml,"__esModule",{value:!0});var ES=gt(),_s=F(),US=te(),OS=te(),hE={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,ES.allSchemaProperties)(r),d=c.filter(S=>(0,US.alwaysValidSchema)(i,r[S]));if(c.length===0||d.length===c.length&&(!i.opts.unevaluated||i.props===!0))return;let p=s.strictSchema&&!s.allowMatchingProperties&&a.properties,l=t.name("valid");i.props!==!0&&!(i.props instanceof _s.Name)&&(i.props=(0,OS.evaluatedPropsToName)(t,i.props));let{props:m}=i;h();function h(){for(let S of c)p&&y(S),i.allErrors?v(S):(t.var(l,!0),v(S),t.if(l))}o(h,"validatePatternProperties");function y(S){for(let _ in p)new RegExp(S).test(_)&&(0,US.checkStrictMode)(i,`property ${_} matches pattern ${S} (use allowMatchingProperties)`)}o(y,"checkMatchingProperties");function v(S){t.forIn("key",n,_=>{t.if((0,_s._)`${(0,ES.usePattern)(e,S)}.test(${_})`,()=>{let w=d.includes(S);w||e.subschema({keyword:"patternProperties",schemaProp:S,dataProp:_,dataPropType:OS.Type.Str},l),i.opts.unevaluated&&m!==!0?t.assign((0,_s._)`${m}[${_}]`,!0):!w&&!i.allErrors&&t.if((0,_s.not)(l),()=>t.break())})})}o(v,"validateProperties")}};Ml.default=hE});var MS=k(zl=>{"use strict";Object.defineProperty(zl,"__esModule",{value:!0});var gE=te(),yE={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(e){let{gen:t,schema:r,it:n}=e;if((0,gE.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=yE});var zS=k(ql=>{"use strict";Object.defineProperty(ql,"__esModule",{value:!0});var SE=gt(),vE={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:SE.validateUnion,error:{message:"must match a schema in anyOf"}};ql.default=vE});var qS=k(Nl=>{"use strict";Object.defineProperty(Nl,"__esModule",{value:!0});var ws=F(),_E=te(),wE={message:"must match exactly one schema in oneOf",params:o(({params:e})=>(0,ws._)`{passingSchemas: ${e.passing}}`,"params")},bE={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:wE,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,_E.alwaysValidSchema)(a,l)?t.var(d,!0):h=e.subschema({keyword:"oneOf",schemaProp:m,compositeRule:!0},d),m>0&&t.if((0,ws._)`${d} && ${s}`).assign(s,!1).assign(c,(0,ws._)`[${c}, ${m}]`).else(),t.if(d,()=>{t.assign(s,!0),t.assign(c,m),h&&e.mergeEvaluated(h,ws.Name)})})}o(p,"validateOneOf")}};Nl.default=bE});var NS=k(jl=>{"use strict";Object.defineProperty(jl,"__esModule",{value:!0});var RE=te(),CE={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,RE.alwaysValidSchema)(n,i))return;let c=e.subschema({keyword:"allOf",schemaProp:s},a);e.ok(a),e.mergeEvaluated(c)})}};jl.default=CE});var HS=k(Dl=>{"use strict";Object.defineProperty(Dl,"__esModule",{value:!0});var bs=F(),DS=te(),IE={message:o(({params:e})=>(0,bs.str)`must match "${e.ifClause}" schema`,"message"),params:o(({params:e})=>(0,bs._)`{failingKeyword: ${e.ifClause}}`,"params")},PE={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:IE,code(e){let{gen:t,parentSchema:r,it:n}=e;r.then===void 0&&r.else===void 0&&(0,DS.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let a=jS(n,"then"),i=jS(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,bs.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,bs._)`${l}`):e.setParams({ifClause:l})}}o(p,"validateClause")}};function jS(e,t){let r=e.schema[t];return r!==void 0&&!(0,DS.alwaysValidSchema)(e,r)}o(jS,"hasSchema");Dl.default=PE});var LS=k(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});var xE=te(),kE={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:e,parentSchema:t,it:r}){t.if===void 0&&(0,xE.checkStrictMode)(r,`"${e}" without "if" is ignored`)}};Hl.default=kE});var BS=k(Ll=>{"use strict";Object.defineProperty(Ll,"__esModule",{value:!0});var TE=Cl(),AE=vS(),EE=Il(),UE=wS(),OE=bS(),$E=IS(),ME=xS(),zE=Ul(),qE=AS(),NE=$S(),jE=MS(),DE=zS(),HE=qS(),LE=NS(),BE=HS(),GE=LS();function VE(e=!1){let t=[jE.default,DE.default,HE.default,LE.default,BE.default,GE.default,ME.default,zE.default,$E.default,qE.default,NE.default];return e?t.push(AE.default,UE.default):t.push(TE.default,EE.default),t.push(OE.default),t}o(VE,"getApplicator");Ll.default=VE});var GS=k(Bl=>{"use strict";Object.defineProperty(Bl,"__esModule",{value:!0});var Re=F(),FE={message:o(({schemaCode:e})=>(0,Re.str)`must match format "${e}"`,"message"),params:o(({schemaCode:e})=>(0,Re._)`{format: ${e}}`,"params")},ZE={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:FE,code(e,t){let{gen:r,data:n,$data:a,schema:i,schemaCode:s,it:c}=e,{opts:d,errSchemaPath:p,schemaEnv:l,self:m}=c;if(!d.validateFormats)return;a?h():y();function h(){let v=r.scopeValue("formats",{ref:m.formats,code:d.code.formats}),S=r.const("fDef",(0,Re._)`${v}[${s}]`),_=r.let("fType"),w=r.let("format");r.if((0,Re._)`typeof ${S} == "object" && !(${S} instanceof RegExp)`,()=>r.assign(_,(0,Re._)`${S}.type || "string"`).assign(w,(0,Re._)`${S}.validate`),()=>r.assign(_,(0,Re._)`"string"`).assign(w,S)),e.fail$data((0,Re.or)(b(),R()));function b(){return d.strictSchema===!1?Re.nil:(0,Re._)`${s} && !${w}`}o(b,"unknownFmt");function R(){let z=l.$async?(0,Re._)`(${S}.async ? await ${w}(${n}) : ${w}(${n}))`:(0,Re._)`${w}(${n})`,q=(0,Re._)`(typeof ${w} == "function" ? ${z} : ${w}.test(${n}))`;return(0,Re._)`${w} && ${w} !== true && ${_} === ${t} && !${q}`}o(R,"invalidFmt")}o(h,"validate$DataFormat");function y(){let v=m.formats[i];if(!v){b();return}if(v===!0)return;let[S,_,w]=R(v);S===t&&e.pass(z());function b(){if(d.strictSchema===!1){m.logger.warn(q());return}throw new Error(q());function q(){return`unknown format "${i}" ignored in schema at path "${p}"`}}o(b,"unknownFormat");function R(q){let je=q instanceof RegExp?(0,Re.regexpCode)(q):d.code.formats?(0,Re._)`${d.code.formats}${(0,Re.getProperty)(i)}`:void 0,ut=r.scopeValue("formats",{key:i,ref:q,code:je});return typeof q=="object"&&!(q instanceof RegExp)?[q.type||"string",q.validate,(0,Re._)`${ut}.validate`]:["string",q,ut]}o(R,"getFormat");function z(){if(typeof v=="object"&&!(v instanceof RegExp)&&v.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Re._)`await ${w}(${n})`}return typeof _=="function"?(0,Re._)`${w}(${n})`:(0,Re._)`${w}.test(${n})`}o(z,"validCondition")}o(y,"validateFormat")}};Bl.default=ZE});var VS=k(Gl=>{"use strict";Object.defineProperty(Gl,"__esModule",{value:!0});var KE=GS(),JE=[KE.default];Gl.default=JE});var FS=k(to=>{"use strict";Object.defineProperty(to,"__esModule",{value:!0});to.contentVocabulary=to.metadataVocabulary=void 0;to.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];to.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var KS=k(Vl=>{"use strict";Object.defineProperty(Vl,"__esModule",{value:!0});var WE=tS(),YE=hS(),QE=BS(),XE=VS(),ZS=FS(),eU=[WE.default,YE.default,(0,QE.default)(),XE.default,ZS.metadataVocabulary,ZS.contentVocabulary];Vl.default=eU});var WS=k(Rs=>{"use strict";Object.defineProperty(Rs,"__esModule",{value:!0});Rs.DiscrError=void 0;var JS;(function(e){e.Tag="tag",e.Mapping="mapping"})(JS||(Rs.DiscrError=JS={}))});var QS=k(Zl=>{"use strict";Object.defineProperty(Zl,"__esModule",{value:!0});var ro=F(),Fl=WS(),YS=os(),tU=Sa(),rU=te(),nU={message:o(({params:{discrError:e,tagName:t}})=>e===Fl.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,"message"),params:o(({params:{discrError:e,tag:t,tagName:r}})=>(0,ro._)`{error: ${e}, tag: ${r}, tagValue: ${t}}`,"params")},oU={keyword:"discriminator",type:"object",schemaType:"object",error:nU,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,ro._)`${r}${(0,ro.getProperty)(c)}`);t.if((0,ro._)`typeof ${p} == "string"`,()=>l(),()=>e.error(!1,{discrError:Fl.DiscrError.Tag,tag:p,tagName:c})),e.ok(d);function l(){let y=h();t.if(!1);for(let v in y)t.elseIf((0,ro._)`${p} === ${v}`),t.assign(d,m(y[v]));t.else(),e.error(!1,{discrError:Fl.DiscrError.Mapping,tag:p,tagName:c}),t.endIf()}o(l,"validateMapping");function m(y){let v=t.name("valid"),S=e.subschema({keyword:"oneOf",schemaProp:y},v);return e.mergeEvaluated(S,ro.Name),v}o(m,"applyTagSchema");function h(){var y;let v={},S=w(a),_=!0;for(let z=0;z<s.length;z++){let q=s[z];if(q?.$ref&&!(0,rU.schemaHasRulesButRef)(q,i.self.RULES)){let ut=q.$ref;if(q=YS.resolveRef.call(i.self,i.schemaEnv.root,i.baseId,ut),q instanceof YS.SchemaEnv&&(q=q.schema),q===void 0)throw new tU.default(i.opts.uriResolver,i.baseId,ut)}let je=(y=q?.properties)===null||y===void 0?void 0:y[c];if(typeof je!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${c}"`);_=_&&(S||w(q)),b(je,z)}if(!_)throw new Error(`discriminator: "${c}" must be required`);return v;function w({required:z}){return Array.isArray(z)&&z.includes(c)}function b(z,q){if(z.const)R(z.const,q);else if(z.enum)for(let je of z.enum)R(je,q);else throw new Error(`discriminator: "properties/${c}" must have "const" or "enum"`)}function R(z,q){if(typeof z!="string"||z in v)throw new Error(`discriminator: "${c}" values must be unique strings`);v[z]=q}}o(h,"getMapping")}};Zl.default=oU});var XS=k((rZ,aU)=>{aU.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"http://json-schema.org/draft-07/schema#",title:"Core schema meta-schema",definitions:{schemaArray:{type:"array",minItems:1,items:{$ref:"#"}},nonNegativeInteger:{type:"integer",minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:"#/definitions/nonNegativeInteger"},{default:0}]},simpleTypes:{enum:["array","boolean","integer","null","number","object","string"]},stringArray:{type:"array",items:{type:"string"},uniqueItems:!0,default:[]}},type:["object","boolean"],properties:{$id:{type:"string",format:"uri-reference"},$schema:{type:"string",format:"uri"},$ref:{type:"string",format:"uri-reference"},$comment:{type:"string"},title:{type:"string"},description:{type:"string"},default:!0,readOnly:{type:"boolean",default:!1},examples:{type:"array",items:!0},multipleOf:{type:"number",exclusiveMinimum:0},maximum:{type:"number"},exclusiveMaximum:{type:"number"},minimum:{type:"number"},exclusiveMinimum:{type:"number"},maxLength:{$ref:"#/definitions/nonNegativeInteger"},minLength:{$ref:"#/definitions/nonNegativeIntegerDefault0"},pattern:{type:"string",format:"regex"},additionalItems:{$ref:"#"},items:{anyOf:[{$ref:"#"},{$ref:"#/definitions/schemaArray"}],default:!0},maxItems:{$ref:"#/definitions/nonNegativeInteger"},minItems:{$ref:"#/definitions/nonNegativeIntegerDefault0"},uniqueItems:{type:"boolean",default:!1},contains:{$ref:"#"},maxProperties:{$ref:"#/definitions/nonNegativeInteger"},minProperties:{$ref:"#/definitions/nonNegativeIntegerDefault0"},required:{$ref:"#/definitions/stringArray"},additionalProperties:{$ref:"#"},definitions:{type:"object",additionalProperties:{$ref:"#"},default:{}},properties:{type:"object",additionalProperties:{$ref:"#"},default:{}},patternProperties:{type:"object",additionalProperties:{$ref:"#"},propertyNames:{format:"regex"},default:{}},dependencies:{type:"object",additionalProperties:{anyOf:[{$ref:"#"},{$ref:"#/definitions/stringArray"}]}},propertyNames:{$ref:"#"},const:!0,enum:{type:"array",items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:"#/definitions/simpleTypes"},{type:"array",items:{$ref:"#/definitions/simpleTypes"},minItems:1,uniqueItems:!0}]},format:{type:"string"},contentMediaType:{type:"string"},contentEncoding:{type:"string"},if:{$ref:"#"},then:{$ref:"#"},else:{$ref:"#"},allOf:{$ref:"#/definitions/schemaArray"},anyOf:{$ref:"#/definitions/schemaArray"},oneOf:{$ref:"#/definitions/schemaArray"},not:{$ref:"#"}},default:!0}});var Jl=k((me,Kl)=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.MissingRefError=me.ValidationError=me.CodeGen=me.Name=me.nil=me.stringify=me.str=me._=me.KeywordCxt=me.Ajv=void 0;var iU=Jy(),sU=KS(),cU=QS(),ev=XS(),uU=["/properties"],Cs="http://json-schema.org/draft-07/schema",no=class extends iU.default{static{o(this,"Ajv")}_addVocabularies(){super._addVocabularies(),sU.default.forEach(t=>this.addVocabulary(t)),this.opts.discriminator&&this.addKeyword(cU.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let t=this.opts.$data?this.$dataMetaSchema(ev,uU):ev;this.addMetaSchema(t,Cs,!1),this.refs["http://json-schema.org/schema"]=Cs}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Cs)?Cs:void 0)}};me.Ajv=no;Kl.exports=me=no;Kl.exports.Ajv=no;Object.defineProperty(me,"__esModule",{value:!0});me.default=no;var dU=ya();Object.defineProperty(me,"KeywordCxt",{enumerable:!0,get:o(function(){return dU.KeywordCxt},"get")});var oo=F();Object.defineProperty(me,"_",{enumerable:!0,get:o(function(){return oo._},"get")});Object.defineProperty(me,"str",{enumerable:!0,get:o(function(){return oo.str},"get")});Object.defineProperty(me,"stringify",{enumerable:!0,get:o(function(){return oo.stringify},"get")});Object.defineProperty(me,"nil",{enumerable:!0,get:o(function(){return oo.nil},"get")});Object.defineProperty(me,"Name",{enumerable:!0,get:o(function(){return oo.Name},"get")});Object.defineProperty(me,"CodeGen",{enumerable:!0,get:o(function(){return oo.CodeGen},"get")});var lU=rs();Object.defineProperty(me,"ValidationError",{enumerable:!0,get:o(function(){return lU.default},"get")});var pU=Sa();Object.defineProperty(me,"MissingRefError",{enumerable:!0,get:o(function(){return pU.default},"get")})});var cv=k(qt=>{"use strict";Object.defineProperty(qt,"__esModule",{value:!0});qt.formatNames=qt.fastFormats=qt.fullFormats=void 0;function zt(e,t){return{validate:e,compare:t}}o(zt,"fmtDef");qt.fullFormats={date:zt(ov,Xl),time:zt(Yl(!0),ep),"date-time":zt(tv(!0),iv),"iso-time":zt(Yl(),av),"iso-date-time":zt(tv(),sv),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:SU,"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:IU,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:vU,int32:{type:"number",validate:bU},int64:{type:"number",validate:RU},float:{type:"number",validate:nv},double:{type:"number",validate:nv},password:!0,binary:!0};qt.fastFormats={...qt.fullFormats,date:zt(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Xl),time:zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,ep),"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,iv),"iso-time":zt(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,av),"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,sv),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};qt.formatNames=Object.keys(qt.fullFormats);function mU(e){return e%4===0&&(e%100!==0||e%400===0)}o(mU,"isLeapYear");var fU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,hU=[0,31,28,31,30,31,30,31,31,30,31,30,31];function ov(e){let t=fU.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:hU[n])}o(ov,"date");function Xl(e,t){if(e&&t)return e>t?1:e<t?-1:0}o(Xl,"compareDate");var Wl=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function Yl(e){return o(function(r){let n=Wl.exec(r);if(!n)return!1;let a=+n[1],i=+n[2],s=+n[3],c=n[4],d=n[5]==="-"?-1:1,p=+(n[6]||0),l=+(n[7]||0);if(p>23||l>59||e&&!c)return!1;if(a<=23&&i<=59&&s<60)return!0;let m=i-l*d,h=a-p*d-(m<0?1:0);return(h===23||h===-1)&&(m===59||m===-1)&&s<61},"time")}o(Yl,"getTime");function ep(e,t){if(!(e&&t))return;let r=new Date("2020-01-01T"+e).valueOf(),n=new Date("2020-01-01T"+t).valueOf();if(r&&n)return r-n}o(ep,"compareTime");function av(e,t){if(!(e&&t))return;let r=Wl.exec(e),n=Wl.exec(t);if(r&&n)return e=r[1]+r[2]+r[3],t=n[1]+n[2]+n[3],e>t?1:e<t?-1:0}o(av,"compareIsoTime");var Ql=/t|\s/i;function tv(e){let t=Yl(e);return o(function(n){let a=n.split(Ql);return a.length===2&&ov(a[0])&&t(a[1])},"date_time")}o(tv,"getDateTime");function iv(e,t){if(!(e&&t))return;let r=new Date(e).valueOf(),n=new Date(t).valueOf();if(r&&n)return r-n}o(iv,"compareDateTime");function sv(e,t){if(!(e&&t))return;let[r,n]=e.split(Ql),[a,i]=t.split(Ql),s=Xl(r,a);if(s!==void 0)return s||ep(n,i)}o(sv,"compareIsoDateTime");var gU=/\/|:/,yU=/^(?:[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 SU(e){return gU.test(e)&&yU.test(e)}o(SU,"uri");var rv=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function vU(e){return rv.lastIndex=0,rv.test(e)}o(vU,"byte");var _U=-(2**31),wU=2**31-1;function bU(e){return Number.isInteger(e)&&e<=wU&&e>=_U}o(bU,"validateInt32");function RU(e){return Number.isInteger(e)}o(RU,"validateInt64");function nv(){return!0}o(nv,"validateNumber");var CU=/[^\\]\\Z/;function IU(e){if(CU.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}o(IU,"regex")});var uv=k(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.formatLimitDefinition=void 0;var PU=Jl(),Pt=F(),Er=Pt.operators,Is={formatMaximum:{okStr:"<=",ok:Er.LTE,fail:Er.GT},formatMinimum:{okStr:">=",ok:Er.GTE,fail:Er.LT},formatExclusiveMaximum:{okStr:"<",ok:Er.LT,fail:Er.GTE},formatExclusiveMinimum:{okStr:">",ok:Er.GT,fail:Er.LTE}},xU={message:o(({keyword:e,schemaCode:t})=>(0,Pt.str)`should be ${Is[e].okStr} ${t}`,"message"),params:o(({keyword:e,schemaCode:t})=>(0,Pt._)`{comparison: ${Is[e].okStr}, limit: ${t}}`,"params")};ao.formatLimitDefinition={keyword:Object.keys(Is),type:"string",schemaType:"string",$data:!0,error:xU,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 PU.KeywordCxt(i,c.RULES.all.format.definition,"format");d.$data?p():l();function p(){let h=t.scopeValue("formats",{ref:c.formats,code:s.code.formats}),y=t.const("fmt",(0,Pt._)`${h}[${d.schemaCode}]`);e.fail$data((0,Pt.or)((0,Pt._)`typeof ${y} != "object"`,(0,Pt._)`${y} instanceof RegExp`,(0,Pt._)`typeof ${y}.compare != "function"`,m(y)))}o(p,"validate$DataFormat");function l(){let h=d.schema,y=c.formats[h];if(!y||y===!0)return;if(typeof y!="object"||y instanceof RegExp||typeof y.compare!="function")throw new Error(`"${a}": format "${h}" does not define "compare" function`);let v=t.scopeValue("formats",{key:h,ref:y,code:s.code.formats?(0,Pt._)`${s.code.formats}${(0,Pt.getProperty)(h)}`:void 0});e.fail$data(m(v))}o(l,"validateFormat");function m(h){return(0,Pt._)`${h}.compare(${r}, ${n}) ${Is[a].fail} 0`}o(m,"compareCode")},dependencies:["format"]};var kU=o(e=>(e.addKeyword(ao.formatLimitDefinition),e),"formatLimitPlugin");ao.default=kU});var mv=k((Ua,pv)=>{"use strict";Object.defineProperty(Ua,"__esModule",{value:!0});var io=cv(),TU=uv(),tp=F(),dv=new tp.Name("fullFormats"),AU=new tp.Name("fastFormats"),rp=o((e,t={keywords:!0})=>{if(Array.isArray(t))return lv(e,t,io.fullFormats,dv),e;let[r,n]=t.mode==="fast"?[io.fastFormats,AU]:[io.fullFormats,dv],a=t.formats||io.formatNames;return lv(e,a,r,n),t.keywords&&(0,TU.default)(e),e},"formatsPlugin");rp.get=(e,t="full")=>{let n=(t==="fast"?io.fastFormats:io.fullFormats)[e];if(!n)throw new Error(`Unknown format "${e}"`);return n};function lv(e,t,r,n){var a,i;(a=(i=e.opts.code).formats)!==null&&a!==void 0||(i.formats=(0,tp._)`require("ajv-formats/dist/formats").${n}`);for(let s of t)e.addFormat(s,r[s])}o(lv,"addFormats");pv.exports=Ua=rp;Object.defineProperty(Ua,"__esModule",{value:!0});Ua.default=rp});var Cn={runtime:{invalid_request:{code:"invalid_request",seam:"runtime",status:400,title:"Bad Request",publicDetail:"The request did not match the route contract.",oauthError:"invalid_request"},forbidden:{code:"forbidden",seam:"runtime",status:403,title:"Forbidden",publicDetail:"The request is not allowed.",oauthError:"invalid_request"},not_found:{code:"not_found",seam:"runtime",status:404,title:"Not Found",publicDetail:"The requested resource was not found.",oauthError:"invalid_request"},internal_server_error:{code:"internal_server_error",seam:"runtime",status:500,title:"Internal Server Error",publicDetail:"The gateway failed to process the request.",oauthError:"server_error"}},config:{virtual_server_not_enabled:{code:"virtual_server_not_enabled",seam:"config",status:404,title:"Not Found",publicDetail:"The requested virtual server is not enabled."},unknown_upstream_server:{code:"unknown_upstream_server",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested upstream server is not configured.",oauthError:"invalid_request"},unknown_virtual_server:{code:"unknown_virtual_server",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested virtual server is not configured.",oauthError:"invalid_target"},unknown_auth_profile:{code:"unknown_auth_profile",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested upstream auth profile is not configured.",oauthError:"invalid_request"},virtual_server_upstream_mismatch:{code:"virtual_server_upstream_mismatch",seam:"config",status:400,title:"Bad Request",publicDetail:"The requested virtual server does not belong to the selected upstream server.",oauthError:"invalid_request"}},downstream_auth:{authentication_required:{code:"authentication_required",seam:"downstream_auth",status:401,title:"Unauthorized",publicDetail:"Authentication is required to access this route.",oauthError:"invalid_client"},identity_context_missing:{code:"identity_context_missing",seam:"downstream_auth",status:403,title:"Forbidden",publicDetail:"Authenticated requests must include a gateway principal subject.",oauthError:"invalid_request"}},downstream_oauth:{browser_login_verification_failed:{code:"browser_login_verification_failed",seam:"downstream_oauth",status:400,title:"Connection failed",publicDetail:"The gateway could not verify the browser login response. Retry the login flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_auth:{provider_access_denied:{code:"provider_access_denied",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream authorization request was denied. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_invalid:{code:"oauth_state_invalid",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream connection request could not be verified. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_expired:{code:"oauth_state_expired",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream connection request expired. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_state_reused:{code:"oauth_state_reused",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"This upstream connection request was already used. Start the connection flow again.",callbackFailure:!0,oauthError:"invalid_request"},oauth_callback_mismatch:{code:"oauth_callback_mismatch",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream callback did not match the initiating connection request.",callbackFailure:!0,oauthError:"invalid_request"},upstream_token_exchange_failed:{code:"upstream_token_exchange_failed",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The gateway could not complete the upstream token exchange. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"},upstream_client_registration_required:{code:"upstream_client_registration_required",seam:"upstream_auth",status:400,title:"Upstream OAuth client registration required",publicDetail:"The upstream authorization server supports neither gateway-hosted Client ID Metadata Documents nor Dynamic Client Registration. Register an upstream OAuth client manually before retrying.",oauthError:"invalid_request"},upstream_token_response_invalid:{code:"upstream_token_response_invalid",seam:"upstream_auth",status:400,title:"Connection failed",publicDetail:"The upstream token response was invalid. Retry the connection flow.",callbackFailure:!0,oauthError:"invalid_request"}},upstream_mcp:{upstream_capability_invocation_failed:{code:"upstream_capability_invocation_failed",seam:"upstream_mcp",status:502,title:"Bad Gateway",publicDetail:"The upstream capability invocation failed. Retry later or reconnect the upstream if the issue persists."},upstream_import_failed:{code:"upstream_import_failed",seam:"upstream_mcp",status:502,title:"Bad Gateway",publicDetail:"The upstream capability import failed. Retry later or reconnect the upstream if the issue persists."}}},am={...Cn.runtime,...Cn.config,...Cn.downstream_auth,...Cn.downstream_oauth,...Cn.upstream_auth,...Cn.upstream_mcp};function Ro(e){return typeof e=="string"&&Object.hasOwn(am,e)}o(Ro,"isGatewayProblemCode");function Wa(e){return Ro(e)&&Ke(e).callbackFailure===!0}o(Wa,"isGatewayCallbackFailureCode");function Ke(e){return am[e]}o(Ke,"readGatewayProblemDefinition");function im(e){switch(e){case 400:return"invalid_request";case 401:return"authentication_required";case 403:return"forbidden";case 404:return"not_found";default:return"internal_server_error"}}o(im,"readDefaultGatewayProblemCodeForStatus");var sm="gatewayCode";function cm(e){let t=Ke(e);return{title:t.title,body:t.publicDetail}}o(cm,"readGatewayCallbackFailureContent");function ge(e){if(!(e instanceof bn))return;let t=e.extensionMembers?.[sm];return Ro(t)?t:void 0}o(ge,"readGatewayProblemCode");function g(e,t,r){let n=typeof e=="string"?{code:e,...t===void 0?{}:{publicDetail:t,privateDetail:t},...r===void 0?{}:{cause:r}}:e,a=Ke(n.code),i=n.privateDetail??(Ya(n.code)?n.publicDetail??a.publicDetail:a.publicDetail),s=$w(n);return new bn({message:i,extensionMembers:{[sm]:n.code}},s===void 0?void 0:{cause:s})}o(g,"createGatewayRuntimeError");async function dt(e,t,r){let n=Ke(r.code),a=Mw(r.code,r.detail),i=Ya(r.code)?r.title??n.title:n.title,c={problem:{...bo.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),bo.format(c,e,t)}o(dt,"gatewayProblemResponse");function Ya(e){return Ke(e).status<500}o(Ya,"canExposeGatewayProblemDetail");function $w(e){return!e.privateDetail||Ya(e.code)?e.cause:e.cause===void 0?new Error(e.privateDetail):new Error(e.privateDetail,{cause:e.cause})}o($w,"readRuntimeErrorCause");function Mw(e,t){let r=Ke(e);return Ya(e)&&t||r.publicDetail}o(Mw,"readSafeGatewayProblemDetail");ue();ue();var zw=new Set(["localhost","::1"]);function Lt(e){return e.replace(/^\[(.*)\]$/,"$1").replace(/\.+$/,"").toLowerCase()}o(Lt,"normalizeHostname");function xe(e){let t=Lt(e.hostname);return e.protocol==="http:"&&(zw.has(t)||/^127(?:\.\d{1,3}){3}$/.test(t))}o(xe,"isLoopbackHttpUrl");var um=new kt("gateway-route");function dm(e,t){um.set(e,t)}o(dm,"setGatewayRouteContext");function Co(e){return um.get(e)}o(Co,"readGatewayRouteContext");function In(e){let t=Co(e);if(!t)throw g("internal_server_error","Gateway route context has not been set");return t}o(In,"requireGatewayRouteContext");var lm=new kt("mcp-oauth-runtime-config");function Pn(e,t){lm.set(e,t)}o(Pn,"setMcpOAuthRuntimeConfig");function pm(e){let t=lm.get(e);if(!t)throw g("internal_server_error","MCP gateway OAuth config has not been set on the request context. An `mcp-oauth-inbound` policy (or `mcp-auth0-oauth-inbound`) must run before this handler, or the internal OAuth route wrapper must have populated the context.");return t}o(pm,"requireMcpOAuthRuntimeConfig");var Io=u.string().trim().min(1),qw=60,Nw=24*60*60,jw=15*qw,Dw=10*365*Nw,Po={accessTokenTtlSeconds:jw,refreshTokenTtlSeconds:Dw,cimdEnabled:!0},Hw=u.object({issuer:u.url(),jwksUrl:u.url(),audience:Io.optional()}),Lw=u.object({url:u.url(),tokenUrl:u.url().optional(),clientId:Io.optional(),clientSecret:Io.optional(),scope:Io.default("openid profile email"),audience:Io.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(!fm(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]})}),Bw=u.object({accessTokenTtlSeconds:u.coerce.number().int().positive().default(Po.accessTokenTtlSeconds),refreshTokenTtlSeconds:u.coerce.number().int().positive().default(Po.refreshTokenTtlSeconds),cimdEnabled:u.boolean().default(Po.cimdEnabled)}).strict().default(Po),fc=u.object({oidc:Hw,browserLogin:Lw,gateway:Bw.optional().default(Po)}).strict();function mm(e){return fm(e.browserLogin.url)?"local_dev":"federated_oidc"}o(mm,"readBrowserLoginKind");function fm(e){let t;try{t=new URL(e)}catch{return!1}return xe(t)&&t.pathname==="/oauth/dev-login"}o(fm,"isLoopbackDevLoginUrl");function hm(e){return fc.parse(e)}o(hm,"parseMcpOAuthRuntimeConfig");function ke(){let e;try{e=cc()}catch(t){throw g("internal_server_error","MCP gateway OAuth config can only be read during a request. Wrap tests in `runWithRequestContext` and ensure MCP OAuth routes are registered through `McpGatewayPlugin`.",t)}return pm(e)}o(ke,"getGatewayOAuthConfig");ue();var Gw=["shared-oauth","user-oauth","static-secret","user-secret","shared-secret"],Vw=["none","client_secret_basic","client_secret_post"],Je=u.string().min(1).brand(),Te=u.string().min(1).brand(),We=u.string().min(1).brand(),cr=u.string().min(1).brand(),Qa=u.enum(Gw),hc=u.enum(Vw),Xa=u.string().trim().min(1).regex(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,"must be a valid HTTP header name"),gc=u.object({name:Xa,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict();ue();var W=u.string().datetime({offset:!0}).brand();function re(e){return W.parse(e.toISOString())}o(re,"toIsoTimestamp");function Bt(e,t){return new Date(e.getTime()+t*1e3)}o(Bt,"addSeconds");ue();function ae(e){return new URL(e).origin}o(ae,"readGatewayRequestOrigin");function vt(e){return ae(e)}o(vt,"readGatewayOAuthIssuer");function yc(e){return e.length>512?`${e.slice(0,512)}\u2026`:e}o(yc,"truncate");function gm(e){return"cause"in e?e.cause:void 0}o(gm,"readCause");function Ye(e,t,r){if(!(r instanceof Error)){r!=null&&(e[`${t}Message`]=yc(String(r)));return}e[`${t}Name`]=r.name,e[`${t}Message`]=yc(r.message);let n=gm(r);for(let a=1;a<=4&&n instanceof Error;a+=1){let i=a===1?"cause":`cause${a}`;e[`${i}Name`]=n.name,e[`${i}Message`]=yc(n.message),n=gm(n)}}o(Ye,"addErrorLogFields");function lt(e){if(e!==void 0)try{return typeof e=="string"?new URL(e).host:e.host}catch{return}}o(lt,"safeHost");function ym(e,t){let r=Object.entries(t).filter(n=>n[1]!==void 0);r.length!==0&&e.log.setLogProperties?.(Object.fromEntries(r))}o(ym,"setLogProperties");function Sc(e,t){ym(e,{subjectId:t.subjectId})}o(Sc,"applyGatewayPrincipalLogProperties");function Sm(e,t){ym(e,{upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId})}o(Sm,"applyGatewayRouteLogProperties");ue();var Fw=43,Zw=128,Kw=/^[A-Za-z0-9._~-]+$/,vc="S256",ei=u.literal(vc),ti=u.string().min(Fw).max(Zw).regex(Kw);ue();var vm=["none","client_secret_post","client_secret_basic"],_c=[...vm,"private_key_jwt"],Jw=["awaiting_login","awaiting_setup"],Ww=u.string().min(1).brand(),Ae=u.string().min(1).brand(),xo=u.uuid().brand(),pt=u.uuid().brand(),ri=u.uuid().brand(),_m=u.enum(vm),wm=u.enum(_c),y1=u.enum(Jw),bm=u.object({client_id:Ae,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:wm.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."})}),wc=u.object({clientId:Ae,clientName:u.string().min(1),redirectUris:u.array(u.string().min(1)),tokenEndpointAuthMethod:wm,hashedClientSecret:u.string().optional(),clientSecretExpiresAt:W.optional(),clientExpiresAt:W,revokedAt:W.optional(),createdAt:W}),bc=u.object({clientId:Ae,resource:u.string(),virtualServerId:Te,subjectId:Ww,scope:u.string(),roles:u.array(u.string()),createdAt:W,expiresAt:W}),S1=bc.extend({id:pt,redirectUri:u.string(),clientState:u.string().optional(),codeChallenge:u.string(),codeChallengeMethod:ei}),Rc=bc.extend({id:xo,currentRefreshTokenHash:u.string().optional(),previousRefreshTokenHash:u.string().optional(),revokedAt:W.optional(),revokedReason:u.string().optional()}),ni=bc.extend({tokenHash:u.string(),grantId:xo,revokedAt:W.optional()});function Cc(){return pt.parse(crypto.randomUUID())}o(Cc,"createDownstreamAuthorizationTransactionId");function Ic(){return ri.parse(crypto.randomUUID())}o(Ic,"createDownstreamBrowserLoginStateId");function Rm(){return xo.parse(crypto.randomUUID())}o(Rm,"createDownstreamGrantId");var ye="mcp:tools";function Cm(e,t){if(e===t)return!0;let r=new URL(e),n=new URL(t);return xe(r)&&xe(n)&&r.pathname===n.pathname&&r.search===n.search}o(Cm,"redirectUriMatchesRegistration");function Im(e){return xe(e)&&e.pathname==="/oauth/dev-login"}o(Im,"isLoopbackDevLoginUrl");function oi(e,t){return new URL(e,vt(t)).toString()}o(oi,"buildGatewayOAuthUrl");function Pc(e){return new URL(`/mcp/${encodeURIComponent(e.virtualServerId)}`,ae(e.requestUrl)).toString()}o(Pc,"buildScopedAuthorizationServerIssuer");function Yw(e){return new URL(`/oauth/authorize/mcp/${encodeURIComponent(e.virtualServerId)}`,ae(e.requestUrl)).toString()}o(Yw,"buildScopedAuthorizationEndpoint");function xc(e){let t=ke();return{issuer:vt(e),authorization_endpoint:oi("/oauth/authorize",e),token_endpoint:oi("/oauth/token",e),registration_endpoint:oi("/oauth/register",e),revocation_endpoint:oi("/oauth/revoke",e),response_types_supported:["code"],response_modes_supported:["query"],grant_types_supported:["authorization_code","refresh_token"],scopes_supported:[ye],code_challenge_methods_supported:[vc],token_endpoint_auth_methods_supported:_c,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":mm(t)}}o(xc,"buildAuthorizationServerMetadata");function Pm(e){let t=Pc(e);return{...xc(e.requestUrl),issuer:t,authorization_endpoint:Yw(e)}}o(Pm,"buildScopedAuthorizationServerMetadata");var Dr="2025-06-18";async function xm(e,t){try{let r=Te.parse(e.params.virtualServerId),n=Hr(r);return Response.json(Qw(n.virtualServerId,e.url))}catch(r){let n=ge(r);return dt(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(xm,"protectedResourceMetadataHandler");function Qw(e,t){return{resource:ur(e,t),resource_name:e,authorization_servers:[Pc({virtualServerId:e,requestUrl:t})],bearer_methods_supported:["header"],scopes_supported:[ye],mcp_protocol_version:Dr}}o(Qw,"buildProtectedResourceMetadataResponseBody");function ur(e,t){return new URL(`/mcp/${encodeURIComponent(e)}`,ae(t)).toString()}o(ur,"buildCanonicalMcpResourceForVirtualServer");function km(e,t){return new URL(`/.well-known/oauth-protected-resource/mcp/${encodeURIComponent(e)}`,ae(t)).toString()}o(km,"buildProtectedResourceMetadataUrlForVirtualServer");var Xw=u.record(u.string(),u.unknown()),Tm=u.string().min(1),eb=u.union([Tm.transform(e=>[e]),u.array(Tm)]),ve=u.string().min(1).brand(),tb=["zuploSubjectId","zuplo_subject_id","gatewaySubjectId","gateway_subject_id","subjectId","subject_id","https://zuplo.com/subject_id"],rb=["https://zuplo.com/roles","roles","role","permissions","groups"],Am=new kt("gateway-principal");function nb(e){let t=Xw.safeParse(e);return t.success?t.data:{}}o(nb,"toClaimRecord");function ob(e){return e.issues[0]?.message??"Gateway principal is invalid"}o(ob,"readValidationFailureDetail");function ab(e,t,r){for(let i of tb){let s=ve.safeParse(t[i]);if(s.success)return s.data}let n=ve.safeParse(e?.sub);if(!n.success)throw g("identity_context_missing",ob(n.error));let a=typeof t.iss=="string"?t.iss:void 0;return!a||a===vt(r)?n.data:ve.parse(`${a}|${n.data}`)}o(ab,"readNormalizedSubjectId");function ib(e){let t=new Set;for(let r of rb){let n=eb.safeParse(e[r]);if(n.success)for(let a of n.data)t.add(a)}return t.size>0?[...t]:void 0}o(ib,"readRoles");function xn(e,t){let r=nb(e?.data),n={subjectId:ab(e,r,t)},a=ib(r);return a&&(n.roles=a),n}o(xn,"parseGatewayPrincipal");function Em(e){let t=Tc(e);if(!t)throw g("identity_context_missing","Gateway principal has not been hydrated");return t}o(Em,"requireGatewayPrincipal");function Um(e,t){Am.set(e,t)}o(Um,"setGatewayPrincipal");function Tc(e){return Am.get(e)}o(Tc,"readGatewayPrincipal");function ai(e){let r=['realm="OAuth"',`resource_metadata="${kc(km(e.virtualServerId,e.requestUrl))}"`];return e.error!==void 0&&r.push(`error="${e.error}"`),e.errorDescription!==void 0&&r.push(`error_description="${kc(e.errorDescription)}"`),e.scope!==void 0&&r.push(`scope="${kc(e.scope)}"`),`Bearer ${r.join(", ")}`}o(ai,"buildGatewayBearerChallenge");function kc(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(kc,"sanitizeQuotedHeaderParameter");ue();ue();function ii(e){if(e===void 0||e.length===0)return;if(!e.startsWith("/")||e.startsWith("//"))throw g("invalid_request","returnTo must be a same-origin relative path.");let t=new URL(e,"https://gateway.local");if(t.origin!=="https://gateway.local"||t.username||t.password||t.hash||t.pathname.startsWith("//"))throw g("invalid_request","returnTo must be a same-origin relative path without credentials or fragments.");return`${t.pathname}${t.search}`}o(ii,"parseSafeRelativeReturnTo");ue();var sb=["user","shared"],kn=u.enum(sb);function dr(e){return{mode:"user",subjectId:e}}o(dr,"buildUserUpstreamConnectionOwner");function si(){return{mode:"shared"}}o(si,"buildSharedUpstreamConnectionOwner");var Om=u.object({ownerMode:kn,initiatedBySubjectId:ve,ownerSubjectId:ve.optional(),upstreamServerId:Je,authProfileId:We,virtualServerId:Te,returnTo:u.string().min(1).transform(e=>ii(e)).optional()});function $m(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($m,"validateUpstreamOwnerState");var Tn=Om.superRefine($m),Mm=Om.omit({returnTo:!0}).superRefine($m);function ko(e){return Tn.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(ko,"buildUpstreamOwnerState");function An(e){if(e.ownerMode==="shared")return si();if(!e.ownerSubjectId)throw g("oauth_state_invalid","User-owned upstream state is missing the owner subject.");return dr(e.ownerSubjectId)}o(An,"resolveUpstreamConnectionOwnerFromState");var cb=["active","not_connected","reconsent_required"],ub=["basic_auth_app_password","bearer_token"],zm=u.string().trim().min(1).brand(),En=u.uuid().brand(),To=u.uuid().brand(),Ac=u.enum(cb),db=u.enum(ub),qm=u.object({encryptedClientInformation:u.string().optional(),encryptedDiscoveryState:u.string().optional(),connectedBySubjectId:ve.optional()}),lb=qm.extend({encryptedStaticSecret:u.string().optional(),staticSecretKind:db.optional(),staticSecretLabel:u.string().min(1).optional(),staticSecretUsername:u.string().min(1).optional()}).strict(),pb=u.object({id:zm,subjectId:ve.optional(),ownerMode:kn,upstreamServerId:Je,authProfileId:We,status:Ac,encryptedAccessToken:u.string().min(1).optional(),encryptedRefreshToken:u.string().min(1).optional(),scopes:u.array(u.string()),expiresAt:W.optional(),metadata:lb.optional(),createdAt:W,updatedAt:W});function Ec(e,t){e.ownerMode==="user"&&(e.subjectId||t.addIssue({code:u.ZodIssueCode.custom,message:"User-owned upstream connections require subjectId",path:["subjectId"]})),e.ownerMode==="shared"&&e.subjectId!==void 0&&t.addIssue({code:u.ZodIssueCode.custom,message:"Shared upstream connections must not include subjectId",path:["subjectId"]})}o(Ec,"validateUpstreamConnectionOwnerShape");var Un=pb.superRefine(Ec);function lr(e){return JSON.stringify([e.owner.mode,e.owner.mode==="user"?e.owner.subjectId:"",e.upstreamServerId,e.authProfileId])}o(lr,"readUpstreamConnectionLookupKey");var Uc=Tn.extend({id:En,callbackPath:u.string().min(1),expiresAt:W,codeVerifier:u.string().optional(),redirectUri:u.url(),returnOrigin:u.url().optional()}).extend(qm.shape);function Nm(e){let t=e?.status??"not_connected",r={connected:t==="active",status:t};return e?.updatedAt!==void 0&&(r.updatedAt=e.updatedAt),r}o(Nm,"readUpstreamConnectionStatus");function ci(){return zm.parse(`mcpgw2uc_${crypto.randomUUID()}`)}o(ci,"createUpstreamConnectionId");function jm(){return En.parse(crypto.randomUUID())}o(jm,"createOAuthStateId");function Dm(){return To.parse(crypto.randomUUID())}o(Dm,"createBrowserConnectTicketId");ue();var $c=u.discriminatedUnion("mode",[u.object({mode:u.literal("user"),subjectId:ve}).strict(),u.object({mode:u.literal("shared")}).strict()]),Lm=u.object({owner:$c,upstreamServerId:Je,authProfileId:We}).strict(),Bm=u.object({items:u.array(Lm).min(1).max(100)}).strict(),Mc=u.object({items:u.array(u.object({key:u.object({ownerMode:kn,subjectId:ve.optional(),upstreamServerId:Je,authProfileId:We}).strict(),connection:Un.strict().optional()}).strict())}).strict(),Gm=Un.omit({createdAt:!0,updatedAt:!0}).strict().superRefine(Ec),Vm=Un.strict(),Fm=u.object({owner:$c,upstreamServerId:Je,authProfileId:We}).strict(),Zm=u.object({owner:$c,upstreamServerId:Je,authProfileId:We,connection:Un.strict().optional(),connectionStatus:u.object({connected:u.boolean(),status:Ac,updatedAt:Un.shape.updatedAt.optional()}).strict()}).strict(),mb=u.enum(["none","client_secret_basic","client_secret_post","private_key_jwt"]),Lr=u.object({clientId:Ae,clientName:u.string().min(1),tokenEndpointAuthMethod:mb}).strict(),zc=u.discriminatedUnion("method",[u.object({method:u.literal("none"),clientId:Ae}).strict(),u.object({method:u.enum(["client_secret_basic","client_secret_post"]),clientId:Ae,clientSecretHashInput:u.string().min(1)}).strict(),u.object({method:u.literal("private_key_jwt"),clientId:Ae}).strict()]),qc=u.object({id:pt,currentStateHash:u.string().min(1),clientId:Ae,redirectUri:u.string().min(1),resource:u.string().min(1),virtualServerId:Te,clientState:u.string().optional(),scope:u.string(),codeChallenge:u.string().min(1),codeChallengeMethod:u.literal("S256"),createdAt:W,expiresAt:W,consumedAt:W.optional()}).strict(),Hm=qc.omit({id:!0,consumedAt:!0}).extend({transactionId:pt,client:Lr.optional()}).strict(),Nc=u.object({subjectId:ve,roles:u.array(u.string()).optional()}).strict(),fb=qc.extend({phase:u.literal("awaiting_login")}).strict(),Oc=qc.extend({phase:u.literal("awaiting_setup"),principal:Nc}).strict(),hb=u.discriminatedUnion("phase",[fb,Oc]),jc=u.object({transaction:hb,client:Lr}).strict(),Km=wc.omit({revokedAt:!0}).strict(),Jm=u.discriminatedUnion("kind",[u.object({kind:u.literal("registered"),client:Lr}).strict(),u.object({kind:u.literal("already_exists")}).strict()]),Wm=u.object({clientId:Ae}).strict(),Ym=u.discriminatedUnion("kind",[u.object({kind:u.literal("found"),client:wc.strict()}).strict(),u.object({kind:u.literal("missing")}).strict()]),Qm=u.discriminatedUnion("phase",[Hm.extend({phase:u.literal("awaiting_login")}).strict(),Hm.extend({phase:u.literal("awaiting_setup"),principal:Nc}).strict()]),Xm=u.discriminatedUnion("kind",[jc.extend({kind:u.literal("started")}).strict(),u.object({kind:u.literal("invalid_client")}).strict(),u.object({kind:u.literal("redirect_uri_mismatch")}).strict(),u.object({kind:u.literal("already_exists")}).strict()]),ef=u.object({transactionId:pt,currentStateHash:u.string().min(1),now:W}).strict(),tf=u.discriminatedUnion("kind",[jc.extend({kind:u.literal("available")}).strict(),u.object({kind:u.literal("stale_hash")}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("missing")}).strict()]),rf=u.object({transactionId:pt,expectedPhase:u.literal("awaiting_login"),currentStateHash:u.string().min(1),nextStateHash:u.string().min(1),nextPhase:u.literal("awaiting_setup"),principal:Nc,now:W}).strict(),nf=u.discriminatedUnion("kind",[jc.extend({kind:u.literal("advanced")}).strict(),u.object({kind:u.literal("wrong_phase"),current:u.enum(["awaiting_login","awaiting_setup"])}).strict(),u.object({kind:u.literal("stale_hash")}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("missing")}).strict()]),of=u.discriminatedUnion("decision",[u.object({decision:u.literal("approve"),transactionId:pt,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:ve}).strict(),authorizationCodeHash:u.string().min(1),authorizationCodeExpiresAt:W,grantId:xo,now:W}).strict(),u.object({decision:u.literal("cancel"),transactionId:pt,currentStateHash:u.string().min(1),currentPrincipal:u.object({subjectId:ve}).strict(),now:W}).strict()]),af=u.discriminatedUnion("kind",[u.object({kind:u.literal("approved"),transaction:Oc,client:Lr}).strict(),u.object({kind:u.literal("cancelled"),transaction:Oc,client:Lr}).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()]),sf=u.object({clientAuth:zc,codeHash:u.string().min(1),redirectUri:u.string().min(1),resource:u.string().min(1).optional(),codeChallenge:u.string().min(1),currentRefreshTokenHash:u.string().min(1),accessTokenHash:u.string().min(1),grantExpiresAt:W,accessTokenExpiresAt:W,now:W}).strict(),cf=u.discriminatedUnion("kind",[u.object({kind:u.literal("exchanged"),client:Lr,grant:Rc.strict()}).strict(),u.object({kind:u.literal("invalid_client")}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("resource_mismatch")}).strict(),u.object({kind:u.literal("binding_mismatch")}).strict()]),uf=u.object({clientAuth:zc,currentRefreshTokenHash:u.string().min(1),nextRefreshTokenHash:u.string().min(1),accessTokenHash:u.string().min(1),resource:u.string().min(1).optional(),accessTokenExpiresAt:W,now:W}).strict(),df=u.discriminatedUnion("kind",[u.object({kind:u.literal("rotated"),client:Lr,grant:Rc.strict(),accessToken:ni.strict(),matched:u.literal("current")}).strict(),u.object({kind:u.literal("invalid_client")}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("resource_mismatch")}).strict(),u.object({kind:u.literal("revoked")}).strict()]),lf=u.object({clientAuth:zc,tokenHash:u.string().min(1),now:W}).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()]),mf=u.object({tokenHash:u.string().min(1),now:W}).strict(),ff=u.discriminatedUnion("kind",[u.object({kind:u.literal("valid"),record:ni.strict()}).strict(),u.object({kind:u.literal("missing")}).strict(),u.object({kind:u.literal("expired")}).strict(),u.object({kind:u.literal("revoked")}).strict()]),hf=u.object({accessTokenHash:u.string().min(1),resource:u.string().min(1),virtualServerId:Te,upstreamConnectionKeys:u.array(Lm).max(100),now:W}).strict(),gf=u.discriminatedUnion("kind",[u.object({kind:u.literal("authorized"),principal:u.object({subjectId:ve,roles:u.array(u.string())}).strict(),accessToken:ni.strict(),upstreamConnections:Mc.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()]),yf=u.object({record:Uc}).strict(),Sf=u.object({kind:u.literal("saved")}).strict(),vf=u.object({id:En,now:W}).strict(),_f=u.discriminatedUnion("kind",[u.object({kind:u.literal("available"),record:Uc}).strict(),u.object({kind:u.literal("consumed")}).strict(),u.object({kind:u.literal("missing")}).strict()]),wf=u.object({id:To,expiresAt:W,now:W}).strict(),bf=u.discriminatedUnion("kind",[u.object({kind:u.literal("available")}).strict(),u.object({kind:u.literal("consumed")}).strict()]);var Rf=100,gb=new Set(["undefined","null","nan"]);function Cf(e){return e!==null&&typeof e=="object"}o(Cf,"isProblemDetailsShape");var yb="/zups/v2/mcp/storage";function Ee(e){return`${yb}/${e}`}o(Ee,"buildStoragePath");function Sb(){return Ee("upstream-connections/batch-get")}o(Sb,"buildBatchGetUpstreamConnectionsPath");function vb(){return Ee("upstream-connections/upsert")}o(vb,"buildUpsertUpstreamConnectionPath");function _b(){return Ee("authorization/read-setup")}o(_b,"buildReadAuthorizationSetupPath");function wb(){return Ee("oauth/register-client")}o(wb,"buildRegisterClientPath");function bb(){return Ee("oauth/read-client")}o(bb,"buildReadClientPath");function Rb(){return Ee("authorization/start")}o(Rb,"buildStartAuthorizationPath");function Cb(){return Ee("authorization/read-pending")}o(Cb,"buildReadPendingAuthorizationPath");function Ib(){return Ee("authorization/advance-pending")}o(Ib,"buildAdvancePendingAuthorizationPath");function Pb(){return Ee("authorization/decide-setup")}o(Pb,"buildDecideAuthorizationSetupPath");function xb(){return Ee("token/exchange-authorization-code")}o(xb,"buildExchangeAuthorizationCodePath");function kb(){return Ee("token/refresh")}o(kb,"buildRefreshTokenPath");function Tb(){return Ee("token/revoke")}o(Tb,"buildRevokeOAuthTokenPath");function Ab(){return Ee("token/validate-access-token")}o(Ab,"buildValidateAccessTokenPath");function Eb(){return Ee("mcp/authorize-and-load-connections")}o(Eb,"buildAuthorizeAndLoadConnectionsPath");function Ub(){return Ee("upstream-oauth-state/save")}o(Ub,"buildSaveUpstreamOAuthStatePath");function Ob(){return Ee("upstream-oauth-state/consume")}o(Ob,"buildConsumeUpstreamOAuthStatePath");function $b(){return Ee("browser-connect-ticket/consume")}o($b,"buildConsumeBrowserConnectTicketPath");function Mb(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(Mb,"responseKeyMatchesLookup");function zb(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(zb,"authorizationSetupMatchesLookup");function kf(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(kf,"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??"")&&Hc(e.scopes,t.scopes)&&Dc(e.expiresAt,t.expiresAt)&&Nb(e.metadata,t.metadata)}o(qb,"connectionMatchesUpsertRecord");function Dc(e,t){return e===void 0||t===void 0?e===t:Date.parse(e)===Date.parse(t)}o(Dc,"optionalTimestampInstantsMatch");function If(e,t){return Date.parse(e)<=Date.parse(t)}o(If,"timestampInstantIsAtOrBefore");function Hc(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}o(Hc,"stringArraysMatch");function Nb(e,t){let r=Pf(e),n=Pf(t),a=Object.fromEntries(n);return r.length===n.length&&r.every(([i,s])=>a[i]===s)}o(Nb,"metadataMatches");function Pf(e){return Object.entries(e??{}).filter(t=>t[1]!==void 0)}o(Pf,"definedMetadataEntries");function we(e,t){throw g({code:"internal_server_error",privateDetail:e,cause:t})}o(we,"throwInvalidStorageResponse");async function jb(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(jb,"parseRuntimeHttpStorageResponse");function Tf(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];Mb(n.key,a)||we("Gateway Service storage response key did not match the request."),n.connection!==void 0&&!kf(n.connection,a)&&we("Gateway Service storage response connection did not match the response key.")}}o(Tf,"validateUpstreamConnectionItemsMatchLookups");function Db(e,t){zb(e,t)||we("Gateway Service storage response authorization setup did not match the request."),e.connection!==void 0&&!kf(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||!Dc(e.connectionStatus.updatedAt,a))&&we("Gateway Service storage response authorization setup status did not match the connection.")}o(Db,"validateAuthorizationSetupResponseMatchesLookup");function Hb(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(Hb,"validateRegisterClientResponseMatchesRequest");function Lb(e,t){e.kind==="found"&&e.client.clientId!==t.clientId&&we("Gateway Service storage response client did not match the request.")}o(Lb,"validateReadClientResponseMatchesRequest");function Bb(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(Bb,"validateStartAuthorizationResponseMatchesRequest");function xf(e,t){e.kind!=="available"&&e.kind!=="advanced"||((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."))}o(xf,"validatePendingAuthorizationResponseMatchesRequest");function Gb(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(Gb,"validateAuthorizationSetupDecisionResponseMatchesRequest");function Vb(e,t){e.kind==="exchanged"&&(e.client.clientId!==t.clientAuth.clientId||e.client.tokenEndpointAuthMethod!==t.clientAuth.method||e.grant.clientId!==t.clientAuth.clientId||e.grant.currentRefreshTokenHash!==t.currentRefreshTokenHash||!Dc(e.grant.expiresAt,t.grantExpiresAt)||t.resource!==void 0&&e.grant.resource!==t.resource)&&we("Gateway Service storage response authorization-code exchange did not match the request.")}o(Vb,"validateExchangeAuthorizationCodeResponseMatchesRequest");function Fb(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||!If(e.accessToken.expiresAt,t.accessTokenExpiresAt)||!If(e.accessToken.expiresAt,e.grant.expiresAt)||!Jb(e.accessToken,e.grant))&&we("Gateway Service storage response token refresh access token did not match the request."))}o(Fb,"validateRefreshTokenResponseMatchesRequest");function Zb(e,t){e.kind==="valid"&&e.record.tokenHash!==t.tokenHash&&we("Gateway Service storage response access token did not match the request.")}o(Zb,"validateAccessTokenValidationResponseMatchesRequest");function Kb(e,t){e.kind==="authorized"&&((e.accessToken.tokenHash!==t.accessTokenHash||e.accessToken.resource!==t.resource||e.accessToken.virtualServerId!==t.virtualServerId||e.principal.subjectId!==e.accessToken.subjectId||!Hc(e.principal.roles,e.accessToken.roles))&&we("Gateway Service storage response MCP authorization did not match the request."),Tf(e.upstreamConnections,t.upstreamConnectionKeys))}o(Kb,"validateAuthorizeAndLoadConnectionsResponseMatchesRequest");function Jb(e,t){return e.clientId===t.clientId&&e.resource===t.resource&&e.virtualServerId===t.virtualServerId&&e.subjectId===t.subjectId&&e.scope===t.scope&&Hc(e.roles,t.roles)}o(Jb,"accessTokenMatchesGrant");async function Wb(e){try{return await e.clone().json()}catch{return}}o(Wb,"readProblemDetails");async function Yb(e){let t=await Wb(e),r=Cf(t)&&typeof t.status=="number"?t.status:e.status,n=Cf(t)&&Ro(t.code)?t.code:im(r);throw g({code:n,privateDetail:`Gateway Service storage request failed with HTTP ${r}.`})}o(Yb,"throwRuntimeHttpStorageError");var ui=class{static{o(this,"RuntimeHttpStorageClient")}#t;#r;constructor(t){this.#t=t.baseUrl??wo.instance.zuploEdgeApiUrl,this.#r=t.fetch??fetch}#n(t){let r;try{r=new URL(t,this.#t)}catch(n){throw g("internal_server_error",`Gateway Service storage base URL is not a valid URL. Got ${JSON.stringify(this.#t)}. Verify the gateway runtime configuration.`,n)}if(r.protocol!=="https:"&&r.protocol!=="http:")throw g("internal_server_error",`Gateway Service storage base URL must use http(s); got protocol "${r.protocol}" from ${JSON.stringify(this.#t)}.`);if(!r.hostname||gb.has(r.hostname))throw g("internal_server_error",`Gateway Service storage base URL has an invalid hostname "${r.hostname}" (parsed from ${JSON.stringify(this.#t)}). The configured value is likely coerced from an unset environment variable.`);return r}async#e(t){let r=t.requestSchema.parse(t.input),n=this.#n(t.path),a=new Headers({"Content-Type":"application/json"});Kp(a);let i=await this.#r(n,{method:"POST",headers:a,body:JSON.stringify(r)});return i.ok||await Yb(i),{request:r,response:await jb(i,t.responseSchema)}}async batchGetUpstreamConnections(t){if(t.length===0)return[];let r=[],n=new Map,a=t.map(s=>{let c=lr(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+=Rf){let c=r.slice(s,s+Rf);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:vb(),requestSchema:Gm,responseSchema:Vm});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:_b(),requestSchema:Fm,responseSchema:Zm});return Db(n,r),n}async registerClient(t){let{request:r,response:n}=await this.#e({input:t,path:wb(),requestSchema:Km,responseSchema:Jm});return Hb(n,r),n}async readClient(t){let{request:r,response:n}=await this.#e({input:t,path:bb(),requestSchema:Wm,responseSchema:Ym});return Lb(n,r),n}async startAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:Rb(),requestSchema:Qm,responseSchema:Xm});return Bb(n,r),n}async readPendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:Cb(),requestSchema:ef,responseSchema:tf});return xf(n,r),n}async advancePendingAuthorization(t){let{request:r,response:n}=await this.#e({input:t,path:Ib(),requestSchema:rf,responseSchema:nf});return xf(n,r),n}async decideAuthorizationSetup(t){let{request:r,response:n}=await this.#e({input:t,path:Pb(),requestSchema:of,responseSchema:af});return Gb(n,r),n}async saveUpstreamOAuthState(t){let{response:r}=await this.#e({input:t,path:Ub(),requestSchema:yf,responseSchema:Sf});return r}async consumeUpstreamOAuthState(t){let{request:r,response:n}=await this.#e({input:t,path:Ob(),requestSchema:vf,responseSchema:_f});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:$b(),requestSchema:wf,responseSchema:bf});return r}async exchangeAuthorizationCode(t){let{request:r,response:n}=await this.#e({input:t,path:xb(),requestSchema:sf,responseSchema:cf});return Vb(n,r),n}async refreshToken(t){let{request:r,response:n}=await this.#e({input:t,path:kb(),requestSchema:uf,responseSchema:df});return Fb(n,r),n}async revokeOAuthToken(t){let{response:r}=await this.#e({input:t,path:Tb(),requestSchema:lf,responseSchema:pf});return r}async validateAccessToken(t){let{request:r,response:n}=await this.#e({input:t,path:Ab(),requestSchema:mf,responseSchema:ff});return Zb(n,r),n}async authorizeAndLoadConnections(t){let{request:r,response:n}=await this.#e({input:t,path:Eb(),requestSchema:hf,responseSchema:gf});return Kb(n,r),n}async#o(t){let r={items:[...t]},{response:n}=await this.#e({input:r,path:Sb(),requestSchema:Bm,responseSchema:Mc});return Tf(n.items,t),n.items.map(a=>a.connection)}};var Qb="__zuploMcpGatewayStorageBackend",Lc;function Xb(){return new ui({})}o(Xb,"buildProductionStorageBackend");function K(){let e=globalThis[Qb];return e||(Lc||(Lc=Xb()),Lc)}o(K,"getStorage");function eR(e,t){let r=Tc(e),n=Co(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 om(e,{...t,subjectId:r?.subjectId,ownerMode:a,upstreamAuthMode:i,virtualServerName:s,upstreamServerName:c,upstreamServerTitle:d,authProfileId:p})}o(eR,"buildMcpAnalyticsMetadata");function V(e,t){try{e.analyticsContext.addAnalyticsEvent(t.value??1,t.eventType,eR(e,t),t.unit)}catch(r){e.log?.warn?.({event:"mcp_analytics_emit_failed",errorName:r instanceof Error?r.name:"unknown"})}}o(V,"emitMcpAnalyticsEvent");import{base64url as Bc}from"jose";var tR="sha256:",rR=32;function Af(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Af,"copyToArrayBuffer");function Gt(){let e=crypto.getRandomValues(new Uint8Array(rR));return Bc.encode(e)}o(Gt,"createOpaqueToken");async function le(e){let t=await crypto.subtle.digest("SHA-256",Af(new TextEncoder().encode(e)));return`${tR}${Bc.encode(new Uint8Array(t))}`}o(le,"hashOpaqueValue");async function Ef(e){let t=await crypto.subtle.digest("SHA-256",Af(new TextEncoder().encode(e)));return Bc.encode(new Uint8Array(t))}o(Ef,"calculatePkceS256Challenge");function Gc(e){let t=e.headers.get("authorization"),[r,n]=t?.split(/\s+/,2)??[];if(!(r?.toLowerCase()!=="bearer"||!n))return n}o(Gc,"readBearerToken");function nR(e,t,r){return dt(e,t,{code:"authentication_required",detail:"Gateway access token is required.",headers:{"WWW-Authenticate":r}})}o(nR,"gatewayAuthenticationRequiredResponse");function oR(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(oR,"tokenValidationReasonCode");async function aR(e,t,r){let n=await K().validateAccessToken({tokenHash:await le(e),now:re(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=oR(n.kind);throw V(t,{eventType:B.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:r,reasonClass:"auth",reasonCode:a,attributes:{validationKind:n.kind}}),V(t,{eventType:B.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r,httpStatusCode:401,reasonClass:"auth",reasonCode:a}),g("authentication_required","Gateway access token is expired, revoked, or invalid.")}return n.record}o(aR,"validateGatewayAccessToken");function iR(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"),V(t,{eventType:B.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:e.virtualServerId,reasonClass:"auth",reasonCode:"invalid_audience"}),V(t,{eventType:B.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:e.virtualServerId,httpStatusCode:401,reasonClass:"auth",reasonCode:"invalid_audience"}),g("authentication_required","Gateway access token was not issued for this MCP resource.")}o(iR,"assertAccessTokenResource");function sR(e,t,r){return dt(e,t,{code:"forbidden",detail:"Gateway access token is missing the required MCP scope.",headers:{"WWW-Authenticate":ai({virtualServerId:r,requestUrl:e.url,error:"insufficient_scope",errorDescription:`The access token is missing the ${ye} scope required by this MCP resource.`,scope:ye})}})}o(sR,"insufficientScopeResponse");function cR(e){return{subjectId:e.subjectId,roles:e.roles}}o(cR,"principalFromAccessToken");function uR(e){let t=ge(e.error),r={event:"gateway_access_token_rejected",code:t??"authentication_required",virtualServerId:e.virtualServerId};return e.error instanceof Error?(r.errorName=e.error.name,r.errorMessage=e.error.message):e.error!==void 0&&e.error!==null&&(r.errorMessage=String(e.error)),e.context.log.warn(r,"Gateway access token rejected; MCP request denied"),dt(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":ai({virtualServerId:e.virtualServerId,requestUrl:e.request.url,error:"invalid_token",errorDescription:"The access token is expired, malformed, or invalid."})}})}o(uR,"gatewayTokenRejectedResponse");async function Vc(e,t){let r=In(t),n=ur(r.virtualServerId,e.url),a=Gc(e),i=ai({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"),V(t,{eventType:B.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r.virtualServerId,httpStatusCode:401,reasonClass:"auth",reasonCode:"missing_token"}),nR(e,t,i);try{let s=await aR(a,t,r.virtualServerId);if(iR({accessToken:s,resource:n,virtualServerId:r.virtualServerId},t),s.scope!==ye)return t.log.warn({event:"gateway_access_token_insufficient_scope",code:"forbidden",tokenScope:s.scope,requiredScope:ye,virtualServerId:r.virtualServerId,clientId:s.clientId},"Gateway access token does not have the required MCP scope"),V(t,{eventType:B.MCP_AUTH_DOWNSTREAM_TOKEN_REJECTED,outcome:"failure",virtualServerName:r.virtualServerId,reasonClass:"auth",reasonCode:"insufficient_scope",attributes:{tokenScope:s.scope,requiredScope:ye,clientId:s.clientId}}),V(t,{eventType:B.MCP_REQUEST_REJECTED,outcome:"failure",virtualServerName:r.virtualServerId,httpStatusCode:403,reasonClass:"auth",reasonCode:"insufficient_scope"}),sR(e,t,r.virtualServerId);let c=cR(s);return Um(t,c),Sc(t,c),V(t,{eventType:B.MCP_AUTH_DOWNSTREAM_TOKEN_VALIDATED,outcome:"success",virtualServerName:r.virtualServerId,attributes:{clientId:s.clientId}}),e}catch(s){return uR({request:e,context:t,error:s,virtualServerId:r.virtualServerId})}}o(Vc,"gatewayTokenInbound");var On={OAUTH_PROTECTED_RESOURCE_METADATA:"oauth_metadata",VIRTUAL_MCP_SERVER:"gateway",OTHER:"other"},dR="oauth-protected-resource-metadata",lR="/.well-known/oauth-protected-resource/";function pR(e){let r=(typeof e.route.raw=="function"?e.route.raw():void 0)?.operationId;return typeof r=="string"?r:void 0}o(pR,"readRouteOperationId");function mR(e){return e.hasGatewayRouteContext?On.VIRTUAL_MCP_SERVER:e.routeOperationId===dR||e.routeOperationId===void 0&&e.routePath.startsWith(lR)?On.OAUTH_PROTECTED_RESOURCE_METADATA:On.OTHER}o(mR,"classifyAnalyticsRouteSurface");function fR(e){let t=e.route.path;return{routePath:t,routeSurface:mR({routePath:t,routeOperationId:pR(e),hasGatewayRouteContext:Co(e)!==void 0})}}o(fR,"readAnalyticsRequestContext");function hR(e){return e.response.status===405&&e.response.headers.has("allow")&&e.routeSurface===On.VIRTUAL_MCP_SERVER}o(hR,"isIntentionalMethodRejection");function gR(e){return hR(e)||e.response.status===401&&e.routeSurface===On.OAUTH_PROTECTED_RESOURCE_METADATA?"success":e.response.status>=400?"failure":"success"}o(gR,"classifyRequestCompletedOutcome");async function Fc(e,t){let r=Date.now(),n=fR(t);return V(t,{eventType:B.MCP_REQUEST_RECEIVED,outcome:"success",routeSurface:n.routeSurface,httpMethod:e.method}),uc.getContextExtensions(t).addHandlerResponseHook(a=>{let i=gR({response:a,routeSurface:n.routeSurface});V(t,{eventType:B.MCP_REQUEST_COMPLETED,outcome:i,routeSurface:n.routeSurface,httpStatusCode:a.status,httpMethod:e.method,latencyMs:Date.now()-r})}),e}o(Fc,"analyticsContextInbound");function yR(e){return e instanceof Response}o(yR,"isResponse");var Uf="/mcp/";function SR(e){let t=e.route.path;if(!t.startsWith(Uf))throw new de(`Route ${t} is bound to mcp-oauth-inbound but does not match the /mcp/{virtualServerId} convention.`);let r=t.slice(Uf.length);if(!r||r.includes("/"))throw new de(`Route ${t} is bound to mcp-oauth-inbound but must use exactly one /mcp/{virtualServerId} segment.`);return r}o(SR,"readVirtualServerIdFromRoute");async function Ao(e,t){let n={virtualServerId:Te.parse(SR(t))};dm(t,n),Sm(t,n);let a=await Fc(e,t);return yR(a)?a:Vc(a,t)}o(Ao,"mcpOAuthInboundPolicy");function di(e,t,r){let n=e.safeParse(t);if(n.success)return n.data;throw new de(`${r} is misconfigured. Validation failed:
|
|
33
|
+
${vR(n.error)}`,{cause:n.error})}o(di,"parseConfigOrThrow");function vR(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
|
|
34
|
+
`)}o(vR,"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.'}),wR=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(),Zc=class extends Rn{static{o(this,"McpAuth0OAuthInboundPolicy")}#t;constructor(t,r){let n=Of(t,r);super(n,r),this.#t=Mf(n,r)}async handler(t,r){return xt("policy.inbound.mcp-auth0-oauth"),Pn(r,this.#t),Ao(t,r)}};function Of(e,t){return di(wR,e,`MCP Auth0 OAuth policy "${t}"`)}o(Of,"parseAuth0OAuthOptions");function $f(e,t="mcp-auth0-oauth-inbound"){let r=Of(e,t);return Mf(r,t)}o($f,"auth0OptionsToMcpOAuthRuntimeConfig");function Mf(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 de(`MCP Auth0 OAuth policy "${t}" is misconfigured. Check the policy options in policies.json.${c}`,s instanceof Error?{cause:s}:void 0)}}o(Mf,"buildAuth0McpOAuthRuntimeConfig");var Kc=class extends Rn{static{o(this,"McpOAuthInboundPolicy")}#t;constructor(t,r){let n=Jc(t,r);super(n,r),this.#t=n}async handler(t,r){return xt("policy.inbound.mcp-oauth"),Pn(r,this.#t),Ao(t,r)}};function Jc(e,t="mcp-oauth-inbound"){return di(fc,e,`MCP OAuth policy "${t}"`)}o(Jc,"mcpOAuthOptionsToRuntimeConfig");var Wc=["mcp-oauth-inbound","mcp-auth0-oauth-inbound"],zf={"mcp-oauth-inbound":"McpOAuthInboundPolicy","mcp-auth0-oauth-inbound":"McpAuth0OAuthInboundPolicy"};function bR(e,t,r){switch(e){case"mcp-oauth-inbound":return Jc(r,t);case"mcp-auth0-oauth-inbound":return $f(r,t);default:return}}o(bR,"parseMcpOAuthPolicyConfig");function qf(e){return e!==void 0&&Wc.some(t=>t===e)}o(qf,"isMcpOAuthInboundPolicyType");function Yc(e){switch(e.policyType){case"mcp-oauth-inbound":return e.handler.export===zf["mcp-oauth-inbound"];case"mcp-auth0-oauth-inbound":return e.handler.export===zf["mcp-auth0-oauth-inbound"];default:return!1}}o(Yc,"isMcpOAuthRuntimeConfigPolicy");function Nf(e){if(!e)return;let t=e.filter(Yc);if(t.length>1){let a=t.map(i=>`"${i.name}" (${i.policyType})`).join(", ");throw new de(`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=bR(r.policyType,r.name,r.handler.options);if(!n)throw new de(`MCP gateway: policy '${r.name}' has unsupported MCP OAuth policy type '${r.policyType}'.`);return{policyName:r.name,config:n}}o(Nf,"resolveMcpOAuthRuntimeConfigFromPolicies");ue();var pr="2025-11-25",jf="2025-03-26",mr=[pr,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],fr="io.modelcontextprotocol/related-task",pi="2.0",Ie=tm(e=>e!==null&&(typeof e=="object"||typeof e=="function")),Df=fe([f(),X().int()]),Hf=f(),Qj=Ce({ttl:X().optional(),pollInterval:X().optional()}),CR=I({ttl:X().optional()}),IR=I({taskId:f()}),Qc=Ce({progressToken:Df.optional(),[fr]:IR.optional()}),ot=I({_meta:Qc.optional()}),Eo=ot.extend({task:CR.optional()}),Lf=o(e=>Eo.safeParse(e).success,"isTaskAugmentedRequestParams"),Ue=I({method:f(),params:ot.loose().optional()}),mt=I({_meta:Qc.optional()}),ft=I({method:f(),params:mt.loose().optional()}),Oe=Ce({_meta:Qc.optional()}),mi=fe([f(),X().int()]),Bf=I({jsonrpc:U(pi),id:mi,...Ue.shape}).strict(),Tt=o(e=>Bf.safeParse(e).success,"isJSONRPCRequest"),Gf=I({jsonrpc:U(pi),...ft.shape}).strict(),Vf=o(e=>Gf.safeParse(e).success,"isJSONRPCNotification"),Xc=I({jsonrpc:U(pi),id:mi,result:Oe}).strict(),_t=o(e=>Xc.safeParse(e).success,"isJSONRPCResultResponse");var A;(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"})(A||(A={}));var eu=I({jsonrpc:U(pi),id:mi.optional(),error:I({code:X().int(),message:f(),data:_e().optional()})}).strict();var Mn=o(e=>eu.safeParse(e).success,"isJSONRPCErrorResponse");var Br=fe([Bf,Gf,Xc,eu]),Xj=fe([Xc,eu]),Ft=Oe.strict(),PR=mt.extend({requestId:mi.optional(),reason:f().optional()}),fi=ft.extend({method:U("notifications/cancelled"),params:PR}),xR=I({src:f(),mimeType:f().optional(),sizes:C(f()).optional(),theme:nt(["light","dark"]).optional()}),Uo=I({icons:C(xR).optional()}),$n=I({name:f(),title:f().optional()}),zn=$n.extend({...$n.shape,...Uo.shape,version:f(),websiteUrl:f().optional(),description:f().optional()}),kR=pc(I({applyDefaults:oe().optional()}),ce(f(),_e())),TR=mc(e=>e&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,pc(I({form:kR.optional(),url:Ie.optional()}),ce(f(),_e()).optional())),AR=Ce({list:Ie.optional(),cancel:Ie.optional(),requests:Ce({sampling:Ce({createMessage:Ie.optional()}).optional(),elicitation:Ce({create:Ie.optional()}).optional()}).optional()}),ER=Ce({list:Ie.optional(),cancel:Ie.optional(),requests:Ce({tools:Ce({call:Ie.optional()}).optional()}).optional()}),UR=I({experimental:ce(f(),Ie).optional(),sampling:I({context:Ie.optional(),tools:Ie.optional()}).optional(),elicitation:TR.optional(),roots:I({listChanged:oe().optional()}).optional(),tasks:AR.optional(),extensions:ce(f(),Ie).optional()}),OR=ot.extend({protocolVersion:f(),capabilities:UR,clientInfo:zn}),hi=Ue.extend({method:U("initialize"),params:OR}),tu=o(e=>hi.safeParse(e).success,"isInitializeRequest"),$R=I({experimental:ce(f(),Ie).optional(),logging:Ie.optional(),completions:Ie.optional(),prompts:I({listChanged:oe().optional()}).optional(),resources:I({subscribe:oe().optional(),listChanged:oe().optional()}).optional(),tools:I({listChanged:oe().optional()}).optional(),tasks:ER.optional(),extensions:ce(f(),Ie).optional()}),ru=Oe.extend({protocolVersion:f(),capabilities:$R,serverInfo:zn,instructions:f().optional()}),gi=ft.extend({method:U("notifications/initialized"),params:mt.optional()}),Ff=o(e=>gi.safeParse(e).success,"isInitializedNotification"),yi=Ue.extend({method:U("ping"),params:ot.optional()}),MR=I({progress:X(),total:Se(X()),message:Se(f())}),zR=I({...mt.shape,...MR.shape,progressToken:Df}),Si=ft.extend({method:U("notifications/progress"),params:zR}),qR=ot.extend({cursor:Hf.optional()}),Oo=Ue.extend({params:qR.optional()}),$o=Oe.extend({nextCursor:Hf.optional()}),NR=nt(["working","input_required","completed","failed","cancelled"]),Mo=I({taskId:f(),status:NR,ttl:fe([X(),Xp()]),createdAt:f(),lastUpdatedAt:f(),pollInterval:Se(X()),statusMessage:Se(f())}),Zt=Oe.extend({task:Mo}),jR=mt.merge(Mo),zo=ft.extend({method:U("notifications/tasks/status"),params:jR}),vi=Ue.extend({method:U("tasks/get"),params:ot.extend({taskId:f()})}),_i=Oe.merge(Mo),wi=Ue.extend({method:U("tasks/result"),params:ot.extend({taskId:f()})}),eD=Oe.loose(),bi=Oo.extend({method:U("tasks/list")}),Ri=$o.extend({tasks:C(Mo)}),Ci=Ue.extend({method:U("tasks/cancel"),params:ot.extend({taskId:f()})}),Zf=Oe.merge(Mo),Kf=I({uri:f(),mimeType:Se(f()),_meta:ce(f(),_e()).optional()}),Jf=Kf.extend({text:f()}),nu=f().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:"Invalid Base64 string"}),Wf=Kf.extend({blob:nu}),qo=nt(["user","assistant"]),qn=I({audience:C(qo).optional(),priority:X().min(0).max(1).optional(),lastModified:Yp.datetime({offset:!0}).optional()}),Yf=I({...$n.shape,...Uo.shape,uri:f(),description:Se(f()),mimeType:Se(f()),size:Se(X()),annotations:qn.optional(),_meta:Se(Ce({}))}),DR=I({...$n.shape,...Uo.shape,uriTemplate:f(),description:Se(f()),mimeType:Se(f()),annotations:qn.optional(),_meta:Se(Ce({}))}),ou=Oo.extend({method:U("resources/list")}),au=$o.extend({resources:C(Yf)}),iu=Oo.extend({method:U("resources/templates/list")}),su=$o.extend({resourceTemplates:C(DR)}),cu=ot.extend({uri:f()}),HR=cu,uu=Ue.extend({method:U("resources/read"),params:HR}),du=Oe.extend({contents:C(fe([Jf,Wf]))}),lu=ft.extend({method:U("notifications/resources/list_changed"),params:mt.optional()}),LR=cu,BR=Ue.extend({method:U("resources/subscribe"),params:LR}),GR=cu,VR=Ue.extend({method:U("resources/unsubscribe"),params:GR}),FR=mt.extend({uri:f()}),ZR=ft.extend({method:U("notifications/resources/updated"),params:FR}),KR=I({name:f(),description:Se(f()),required:Se(oe())}),JR=I({...$n.shape,...Uo.shape,description:Se(f()),arguments:Se(C(KR)),_meta:Se(Ce({}))}),pu=Oo.extend({method:U("prompts/list")}),mu=$o.extend({prompts:C(JR)}),WR=ot.extend({name:f(),arguments:ce(f(),f()).optional()}),fu=Ue.extend({method:U("prompts/get"),params:WR}),hu=I({type:U("text"),text:f(),annotations:qn.optional(),_meta:ce(f(),_e()).optional()}),gu=I({type:U("image"),data:nu,mimeType:f(),annotations:qn.optional(),_meta:ce(f(),_e()).optional()}),yu=I({type:U("audio"),data:nu,mimeType:f(),annotations:qn.optional(),_meta:ce(f(),_e()).optional()}),YR=I({type:U("tool_use"),name:f(),id:f(),input:ce(f(),_e()),_meta:ce(f(),_e()).optional()}),QR=I({type:U("resource"),resource:fe([Jf,Wf]),annotations:qn.optional(),_meta:ce(f(),_e()).optional()}),XR=Yf.extend({type:U("resource_link")}),Su=fe([hu,gu,yu,XR,QR]),eC=I({role:qo,content:Su}),vu=Oe.extend({description:f().optional(),messages:C(eC)}),_u=ft.extend({method:U("notifications/prompts/list_changed"),params:mt.optional()}),tC=I({title:f().optional(),readOnlyHint:oe().optional(),destructiveHint:oe().optional(),idempotentHint:oe().optional(),openWorldHint:oe().optional()}),rC=I({taskSupport:nt(["required","optional","forbidden"]).optional()}),Qf=I({...$n.shape,...Uo.shape,description:f().optional(),inputSchema:I({type:U("object"),properties:ce(f(),Ie).optional(),required:C(f()).optional()}).catchall(_e()),outputSchema:I({type:U("object"),properties:ce(f(),Ie).optional(),required:C(f()).optional()}).catchall(_e()).optional(),annotations:tC.optional(),execution:rC.optional(),_meta:ce(f(),_e()).optional()}),wu=Oo.extend({method:U("tools/list")}),bu=$o.extend({tools:C(Qf)}),hr=Oe.extend({content:C(Su).default([]),structuredContent:ce(f(),_e()).optional(),isError:oe().optional()}),tD=hr.or(Oe.extend({toolResult:_e()})),nC=Eo.extend({name:f(),arguments:ce(f(),_e()).optional()}),No=Ue.extend({method:U("tools/call"),params:nC}),Ru=ft.extend({method:U("notifications/tools/list_changed"),params:mt.optional()}),Xf=I({autoRefresh:oe().default(!0),debounceMs:X().int().nonnegative().default(300)}),jo=nt(["debug","info","notice","warning","error","critical","alert","emergency"]),oC=ot.extend({level:jo}),Cu=Ue.extend({method:U("logging/setLevel"),params:oC}),aC=mt.extend({level:jo,logger:f().optional(),data:_e()}),iC=ft.extend({method:U("notifications/message"),params:aC}),sC=I({name:f().optional()}),cC=I({hints:C(sC).optional(),costPriority:X().min(0).max(1).optional(),speedPriority:X().min(0).max(1).optional(),intelligencePriority:X().min(0).max(1).optional()}),uC=I({mode:nt(["auto","required","none"]).optional()}),dC=I({type:U("tool_result"),toolUseId:f().describe("The unique identifier for the corresponding tool call."),content:C(Su).default([]),structuredContent:I({}).loose().optional(),isError:oe().optional(),_meta:ce(f(),_e()).optional()}),lC=lc("type",[hu,gu,yu]),li=lc("type",[hu,gu,yu,YR,dC]),pC=I({role:qo,content:fe([li,C(li)]),_meta:ce(f(),_e()).optional()}),mC=Eo.extend({messages:C(pC),modelPreferences:cC.optional(),systemPrompt:f().optional(),includeContext:nt(["none","thisServer","allServers"]).optional(),temperature:X().optional(),maxTokens:X().int(),stopSequences:C(f()).optional(),metadata:Ie.optional(),tools:C(Qf).optional(),toolChoice:uC.optional()}),Iu=Ue.extend({method:U("sampling/createMessage"),params:mC}),Gr=Oe.extend({model:f(),stopReason:Se(nt(["endTurn","stopSequence","maxTokens"]).or(f())),role:qo,content:lC}),Do=Oe.extend({model:f(),stopReason:Se(nt(["endTurn","stopSequence","maxTokens","toolUse"]).or(f())),role:qo,content:fe([li,C(li)])}),fC=I({type:U("boolean"),title:f().optional(),description:f().optional(),default:oe().optional()}),hC=I({type:U("string"),title:f().optional(),description:f().optional(),minLength:X().optional(),maxLength:X().optional(),format:nt(["email","uri","date","date-time"]).optional(),default:f().optional()}),gC=I({type:nt(["number","integer"]),title:f().optional(),description:f().optional(),minimum:X().optional(),maximum:X().optional(),default:X().optional()}),yC=I({type:U("string"),title:f().optional(),description:f().optional(),enum:C(f()),default:f().optional()}),SC=I({type:U("string"),title:f().optional(),description:f().optional(),oneOf:C(I({const:f(),title:f()})),default:f().optional()}),vC=I({type:U("string"),title:f().optional(),description:f().optional(),enum:C(f()),enumNames:C(f()).optional(),default:f().optional()}),_C=fe([yC,SC]),wC=I({type:U("array"),title:f().optional(),description:f().optional(),minItems:X().optional(),maxItems:X().optional(),items:I({type:U("string"),enum:C(f())}),default:C(f()).optional()}),bC=I({type:U("array"),title:f().optional(),description:f().optional(),minItems:X().optional(),maxItems:X().optional(),items:I({anyOf:C(I({const:f(),title:f()}))}),default:C(f()).optional()}),RC=fe([wC,bC]),CC=fe([vC,_C,RC]),IC=fe([CC,fC,hC,gC]),PC=Eo.extend({mode:U("form").optional(),message:f(),requestedSchema:I({type:U("object"),properties:ce(f(),IC),required:C(f()).optional()})}),xC=Eo.extend({mode:U("url"),message:f(),elicitationId:f(),url:f().url()}),kC=fe([PC,xC]),Pu=Ue.extend({method:U("elicitation/create"),params:kC}),TC=mt.extend({elicitationId:f()}),AC=ft.extend({method:U("notifications/elicitation/complete"),params:TC}),gr=Oe.extend({action:nt(["accept","decline","cancel"]),content:mc(e=>e===null?void 0:e,ce(f(),fe([f(),X(),oe(),C(f())])).optional())}),EC=I({type:U("ref/resource"),uri:f()});var UC=I({type:U("ref/prompt"),name:f()}),OC=ot.extend({ref:fe([UC,EC]),argument:I({name:f(),value:f()}),context:I({arguments:ce(f(),f()).optional()}).optional()}),$C=Ue.extend({method:U("completion/complete"),params:OC});var xu=Oe.extend({completion:Ce({values:C(f()).max(100),total:Se(X().int()),hasMore:Se(oe())})}),MC=I({uri:f().startsWith("file://"),name:f().optional(),_meta:ce(f(),_e()).optional()}),zC=Ue.extend({method:U("roots/list"),params:ot.optional()}),ku=Oe.extend({roots:C(MC)}),qC=ft.extend({method:U("notifications/roots/list_changed"),params:mt.optional()}),rD=fe([yi,hi,$C,Cu,fu,pu,ou,iu,uu,BR,VR,No,wu,vi,wi,bi,Ci]),nD=fe([fi,Si,gi,qC,zo]),oD=fe([Ft,Gr,Do,gr,ku,_i,Ri,Zt]),aD=fe([yi,Iu,Pu,zC,vi,wi,bi,Ci]),iD=fe([fi,Si,iC,ZR,lu,Ru,_u,zo,AC]),sD=fe([Ft,ru,xu,vu,mu,au,su,du,hr,bu,_i,Ri,Zt]),x=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===A.UrlElicitationRequired&&n){let a=n;if(a.elicitations)return new Vt(a.elicitations,r)}return new e(t,r,n)}},Vt=class extends x{static{o(this,"UrlElicitationRequiredError")}constructor(t,r=`URL elicitation${t.length>1?"s":""} required`){super(A.UrlElicitationRequired,r,{elicitations:t})}get elicitations(){return this.data?.elicitations??[]}};ue();var rh=Je,NC=u.object({mode:u.literal("auto")}).strict(),jC=u.object({mode:u.literal("manual"),clientId:u.string().trim().min(1),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:hc.default("client_secret_basic")}).strict().superRefine((e,t)=>{e.tokenEndpointAuthMethod!=="none"&&!e.clientSecret&&t.addIssue({code:u.ZodIssueCode.custom,message:`${e.tokenEndpointAuthMethod} requires clientSecret`,path:["clientSecret"]})}),nh=u.discriminatedUnion("mode",[NC,jC]),DC=nh.default({mode:"auto"}),Tu=u.object({scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:DC}).strict(),eh=Tu.extend({redirectPath:u.string().startsWith("/auth/connections/")}).strict(),oh=new Set(["connection","content-length","cookie","host","proxy-authenticate","proxy-authorization","sec-websocket-key","set-cookie","te","trailer","transfer-encoding","upgrade"]),HC=new Set([...oh,"accept","authorization","content-type","mcp-protocol-version","mcp-session-id","proxy-connection"]),LC=u.object({kind:u.literal("bearer_token"),token:u.string().min(1)}).strict(),BC=u.object({kind:u.literal("headers"),headers:u.array(u.object({name:Xa,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();oh.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)}}),Au=u.discriminatedUnion("kind",[LC,BC]),GC=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(),VC=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key"),capture:u.enum(["browser_login"]).optional()}).strict(),Eu=u.discriminatedUnion("kind",[GC,VC]),Uu=u.object({kind:u.literal("bearer_token"),label:u.string().min(1).default("API key")}).strict(),FC=u.discriminatedUnion("mode",[u.object({mode:u.literal("shared-oauth"),oauth:eh}).strict(),u.object({mode:u.literal("user-oauth"),oauth:eh}).strict(),u.object({mode:u.literal("static-secret"),secret:Au}).strict(),u.object({mode:u.literal("user-secret"),secret:Eu}).strict(),u.object({mode:u.literal("shared-secret"),secret:Uu}).strict()]),ZC=u.object({baseUrl:u.url(),resourceMetadataUrl:u.url(),requestHeaders:u.array(gc).default([])}).strict().superRefine((e,t)=>{let r=new Set;for(let[n,a]of e.requestHeaders.entries()){let i=a.name.toLowerCase();HC.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)}}),fD=u.object({displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:zn.optional(),authProfiles:u.record(We,FC),transport:ZC}).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"]})}),KC=u.object({"shared-oauth":Tu.optional(),"user-oauth":Tu.optional(),"static-secret":u.object({secret:Au}).strict().optional(),"user-secret":u.object({secret:Eu}).strict().optional(),"shared-secret":u.object({secret:Uu}).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"})}),th=u.object({id:rh,displayName:u.string().min(1),description:u.string().min(1).optional(),serverInfo:zn.optional(),mcpUrl:u.url(),protectedResourceMetadataUrl:u.url(),requestHeaders:u.array(gc).default([]),authProfiles:KC}).strict(),JC=u.object({name:Xa,value:u.string().min(1).optional(),required:u.boolean().default(!0)}).strict(),Ii={id:rh.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(JC).default([])},WC=u.discriminatedUnion("authMode",[u.object({...Ii,authMode:u.enum(["shared-oauth","user-oauth"]),scopes:u.array(u.string().min(1)).default([]),scopeDelimiter:u.string().min(1).default(" "),clientRegistration:nh.optional(),clientId:u.string().trim().min(1).optional(),clientSecret:u.string().min(1).optional(),tokenEndpointAuthMethod:hc.optional()}).strict(),u.object({...Ii,authMode:u.literal("static-secret"),secret:Au}).strict(),u.object({...Ii,authMode:u.literal("user-secret"),secret:Eu}).strict(),u.object({...Ii,authMode:u.literal("shared-secret"),secret:Uu}).strict()]);function YC(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
|
|
35
|
+
`)}o(YC,"formatZodIssues");function ah(e){throw new de(e)}o(ah,"throwGatewayConfigError");function QC(e){let t="mcp-upstream-";return e.startsWith(t)||ah(`Upstream policy ${e} must use the ${t}{upstream-id} naming convention when id is omitted.`),Je.parse(e.slice(t.length))}o(QC,"inferUpstreamConnectionIdFromPolicyName");function XC(e){let t=new URL(e),r=t.pathname==="/"?"":t.pathname;return`${t.origin}/.well-known/oauth-protected-resource${r}`}o(XC,"buildDefaultProtectedResourceMetadataUrl");function Nn(e,t){return We.parse(`${e}:${t}`)}o(Nn,"buildUpstreamAuthProfileId");function Pi(e,t){try{let r=th.safeParse(e);if(r.success)return r.data;let n=WC.parse(e),a=n.id??(t===void 0?void 0:QC(t));a===void 0&&ah("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 th.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??XC(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 de(`${n} is misconfigured. Missing/invalid options in policies.json:
|
|
36
|
+
${YC(r)}`,{cause:r})}throw r}}o(Pi,"parseUpstreamConnectionPolicyOptions");function ih(e){return e.mode==="shared-oauth"||e.mode==="user-oauth"}o(ih,"isUpstreamOAuthAuthConfig");ue();var eI=u.looseObject({name:u.string().min(1),version:u.string().min(1).optional()}),tI=u.looseObject({}),rI=u.looseObject({name:cr,namespace:cr.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional(),inputSchema:tI}),nI=u.looseObject({name:cr,namespace:cr.optional(),upstreamPolicy:u.string().min(1).optional(),enabled:u.boolean().optional()}),oI=u.looseObject({name:cr,uri:u.string().min(1),upstreamPolicy:u.string().min(1).optional(),upstreamUri:u.string().min(1).optional(),enabled:u.boolean().optional()}),aI=u.enum(["openapi","upstream_mcp"]),iI=u.object({catalogSource:aI.default("openapi"),serverInfo:eI.optional(),tools:u.array(rI).default([]),prompts:u.array(nI).default([]),resources:u.array(oI).default([])}).strict();function sI(e){return e.issues.map(t=>` - ${t.path.length>0?t.path.join("."):"<root>"}: ${t.message}`).join(`
|
|
37
|
+
`)}o(sI,"formatZodIssues");function sh(e,t){let r=iI.safeParse(e??{});if(!r.success){let n=t===void 0?"MCP virtual server route":`MCP virtual server route ${t}`;throw new de(`${n} is misconfigured. Missing/invalid handler options in routes.oas.json:
|
|
38
|
+
${sI(r.error)}`,{cause:r.error})}return r.data}o(sh,"parseVirtualServerRouteOptions");function xi(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(xi,"toMcpTool");function ki(e){let{enabled:t,upstreamName:r,upstreamPolicyName:n,...a}=e;return a}o(ki,"toMcpPrompt");function Ti(e){let{enabled:t,upstreamPolicyName:r,upstreamUri:n,...a}=e;return a}o(Ti,"toMcpResource");var cI="mcp-upstream-connection-inbound",ch="/mcp/";function Pe(e){throw new de(e)}o(Pe,"throwRegistryError");function uI(e){return e.policyType===cI}o(uI,"isUpstreamConnectionPolicy");function dI(e){return qf(e.policyType)}o(dI,"isMcpOAuthInboundPolicy");function lI(e){return e instanceof de?e:new de(e instanceof Error?e.message:"MCP virtual server route is misconfigured.",e instanceof Error?{cause:e}:void 0)}o(lI,"toRouteConfigurationError");function pI(e){e.startsWith(ch)||Pe(`MCP virtual server route ${e} must use a /mcp/{virtualServerId} path.`);let t=e.slice(ch.length);return(!t||t.includes("/"))&&Pe(`MCP virtual server route ${e} must use exactly one /mcp/{virtualServerId} path segment.`),Te.parse(t)}o(pI,"readVirtualServerIdFromPath");function mI(e){let t=Object.keys(e.connection.authProfiles);t.length!==1&&Pe(`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];return r===void 0&&Pe(`Upstream policy ${e.policyName} does not declare an auth mode.`),Qa.parse(r)}o(mI,"readSingleAuthMode");function fI(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||Pe(`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||Pe(`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||Pe(`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||Pe(`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||Pe(`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`),{mode:"shared-secret",secret:r.secret}}}}o(fI,"buildResolvedAuthConfig");function hI(e){let t=mI({policyName:e.policyName,connection:e.connection}),r=Nn(e.connection.id,t),n=fI({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(hI,"buildRegisteredConnection");function gI(e){let t=new Map;for(let r of e)t.has(r.name)&&Pe(`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(gI,"buildPolicyMap");function yI(e){if(typeof e.raw!="function")return;let t=e.raw();if(!(!t||typeof t.operationId!="string"||t.operationId===""))return t.operationId}o(yI,"readOperationId");function uh(e){let t=e.namespace===void 0?e.name:`${e.namespace}.${e.name}`,r=cr.safeParse(t);return r.success||Pe(`MCP virtual server route ${e.routePath} declares invalid published capability name ${t}.`),r.data}o(uh,"buildPublishedCapabilityName");function Mu(e){if(e.authoredPolicyName!==void 0)return e.connections.find(r=>r.policyName===e.authoredPolicyName)||Pe(`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;Pe(`MCP virtual server route ${e.routePath} declares aggregate capability ${e.capabilityName} without upstreamPolicy.`)}o(Mu,"readCapabilityUpstreamPolicy");function Ou(e){e.seen.has(e.key)&&Pe(`MCP virtual server route ${e.routePath} declares duplicate ${e.kind} ${e.key}.`),e.seen.add(e.key)}o(Ou,"assertUniqueCatalogKey");function SI(e){let{namespace:t,upstreamPolicy:r,...n}=e.tool,a=uh({name:e.tool.name,namespace:e.tool.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.tool.name,upstreamPolicyName:Mu({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(SI,"normalizeCatalogTool");function vI(e){let{namespace:t,upstreamPolicy:r,...n}=e.prompt,a=uh({name:e.prompt.name,namespace:e.prompt.namespace,routePath:e.routePath});return{...n,name:a,upstreamName:e.prompt.name,upstreamPolicyName:Mu({authoredPolicyName:r,capabilityName:a,connections:e.connections,routePath:e.routePath})}}o(vI,"normalizeCatalogPrompt");function _I(e){let{upstreamPolicy:t,...r}=e.resource;return{...r,upstreamUri:e.resource.upstreamUri??e.resource.uri,upstreamPolicyName:Mu({authoredPolicyName:t,capabilityName:e.resource.uri,connections:e.connections,routePath:e.routePath})}}o(_I,"normalizeCatalogResource");function wI(e){let t=e.catalog.catalogSource,r=e.catalog.tools.map(d=>SI({tool:d,connections:e.connections,routePath:e.routePath})),n=e.catalog.prompts.map(d=>vI({prompt:d,connections:e.connections,routePath:e.routePath})),a=e.catalog.resources.map(d=>_I({resource:d,connections:e.connections,routePath:e.routePath})),i=new Set;for(let d of r)Ou({kind:"tool",key:d.name,routePath:e.routePath,seen:i});let s=new Set;for(let d of n)Ou({kind:"prompt",key:d.name,routePath:e.routePath,seen:s});let c=new Set;for(let d of a)Ou({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(wI,"normalizeVirtualServerCatalog");function bI(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=Pi(c.handler.options,c.name);a.has(p.id)&&Pe(`Duplicate upstream MCP connection id ${p.id} in policies.json.`),a.add(p.id);let l=hI({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||!dI(l))continue;let m=yI(c),h;try{h=pI(c.path),m||Pe(`MCP virtual server route ${c.path} must declare an operationId in routes.oas.json.`),i.has(m)&&Pe(`Duplicate MCP virtual server operationId ${m} across routes.`),t.has(h)&&Pe(`Duplicate MCP virtual server id ${h} across routes.`);let y=[];for(let _ of d.slice(1)){let w=e.policyByName.get(_);!w||!uI(w)||y.push(s(w))}let v=sh(c.handler.options,c.path),S=wI({catalog:v,connections:y,routePath:c.path});S.catalogSource==="upstream_mcp"&&y.length!==1&&Pe(`MCP virtual server route ${c.path} uses upstream MCP catalog mode but declares ${y.length} upstream bindings; upstream MCP catalog mode requires exactly one upstream binding.`),t.set(h,{virtualServerId:h,operationId:m,routePath:c.path,handlerExport:c.handler.export,serverInfo:S.serverInfo,catalog:S,connections:y}),i.add(m)}catch(y){h!==void 0&&r.set(h,lI(y))}}return{byVirtualServerId:t,virtualServerErrorsById:r,connectionsByPolicyName:n}}o(bI,"buildVirtualServers");function zu(e){let t=gI(e.policies),{byVirtualServerId:r,virtualServerErrorsById:n,connectionsByPolicyName:a}=bI({routes:e.routes,policyByName:t}),i=new Map;for(let s of a.values())i.set(s.upstreamServerId,s);return{byVirtualServerId:r,connectionsById:i,virtualServerErrorsById:n}}o(zu,"buildGatewayConnectionRegistry");var Vr,$u;function dh(e){$u=e,Vr=void 0}o(dh,"configureGatewayConnectionRegistrySource");function lh(e){Vr=e}o(lh,"setGatewayConnectionRegistry");function at(){if(!Vr&&$u&&(Vr=zu($u)),!Vr)throw g("internal_server_error","MCP gateway connection registry has not been initialized. Ensure routes.oas.json declares at least one MCP virtual server route and policies.json registers an `mcp-oauth-inbound` (or wrapper) policy.");return Vr}o(at,"getGatewayConnectionRegistry");function Hr(e){let t=at(),r=t.virtualServerErrorsById?.get(e);if(r)throw r;let n=t.byVirtualServerId.get(e);if(!n)throw g("unknown_virtual_server",`Unknown MCP virtual server: ${e}`);return n}o(Hr,"getRegisteredVirtualServer");function ph(){return Vr}o(ph,"tryGetGatewayConnectionRegistry");function De(e){let t=at().connectionsById.get(e);if(!t)throw g("unknown_upstream_server",`Unknown upstream server: ${e}`);return t.config}o(De,"getUpstreamServerConfig");function RI(e){let t=at().connectionsById.get(e.upstreamServerId);if(!t||t.authProfileId!==e.authProfileId)throw g("unknown_auth_profile",`Unknown auth profile ${String(e.authProfileId)} for upstream server ${e.upstreamServerId}.`);return t.authProfileId}o(RI,"resolveUpstreamAuthProfileId");function yr(e){RI(e);let t=at().connectionsById.get(e.upstreamServerId);if(!t)throw g("unknown_auth_profile",`Auth profile could not be resolved for upstream server ${e.upstreamServerId}.`);return t.authConfig}o(yr,"getUpstreamAuthConfig");function Fr(e,t){let r=yr({upstreamServerId:e,authProfileId:t});if(!ih(r))throw g("invalid_request",`Upstream server ${e} does not use upstream OAuth.`);return r.oauth}o(Fr,"requireUpstreamOAuthConfig");function CI(){let e=Ja.__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(CI,"isTestOnlyAllowHttpLoopbackIdpEnabled");function II(){let e=Ja.__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(II,"isTestOnlyAllowHttpLoopbackCimdEnabled");var PI=new Set(["undefined","null","nan"]);function Nu(e,t){if(!e.hostname)throw g("invalid_request",`Outbound URL has an empty hostname (got ${JSON.stringify(t)}). This typically indicates an unset $env(...) reference or a JS template literal coercing \`undefined\` into a URL. Check the policy options or runtime config that produced this URL.`);if(PI.has(e.hostname.toLowerCase()))throw g("invalid_request",`Outbound URL hostname is ${JSON.stringify(e.hostname)} (from ${JSON.stringify(t)}). This almost always means an environment variable referenced by $env(...) is unset and a JS value was string-coerced into a URL. Set the missing env var or fix the policy option that produced this URL.`)}o(Nu,"assertSafeOutboundHostname");var xI=new Set(["localhost","169.254.169.254","metadata.google.internal","metadata"]),kI=[{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 mh(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(mh,"parseIpv4Octets");function TI([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(TI,"ipv4RangeMatches");function fh(e){let t=mh(e);return t!==void 0&&kI.some(r=>TI(t,r))}o(fh,"isPrivateIpv4");function qu(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(qu,"parseIpv6Word");function AI(e,t){return[e>>8&255,e&255,t>>8&255,t&255].join(".")}o(AI,"formatIpv4FromWords");function EI(e){let t=e.slice(7),r=mh(t);if(r!==void 0)return r.join(".");let[n,a,i]=t.split(":"),s=qu(n),c=qu(a);return i===void 0&&s!==void 0&&c!==void 0?AI(s,c):void 0}o(EI,"parseIpv6MappedIpv4");function UI(e){return qu(e.split(":").find(Boolean))}o(UI,"readFirstIpv6Hextet");function OI(e){let t=Lt(e);if(!t.includes(":"))return!1;if(t==="::"||t==="::1")return!0;if(t.startsWith("::ffff:")){let n=EI(t);return n===void 0||fh(n)}let r=UI(t);return r===void 0?!1:(r&65024)===64512||(r&65472)===65152}o(OI,"isPrivateIpv6");function ju(e){let t=Lt(e);return xI.has(t)||t.endsWith(".internal")||fh(t)||OI(t)}o(ju,"isBlockedOutboundHostname");function hh(e){let t=new URL(e);if(t.protocol!=="https:"&&t.protocol!=="http:")throw g("invalid_request",`Unsupported outbound protocol: ${t.protocol}`);Nu(t,e);let r=xe(t);if(t.protocol==="http:"&&!r)throw g("invalid_request","Configured outbound HTTP URLs must target loopback hosts.");let n=Lt(t.hostname);if(!r&&ju(n))throw g("invalid_request",`Blocked outbound host: ${n}`);return t}o(hh,"validateConfiguredOutboundUrl");function gh(e){let t=new URL(e),r=xe(t),n=r&&CI();if(t.protocol!=="https:"&&!n)throw g("invalid_request","Identity provider URLs must use https.");if(t.username||t.password||t.search||t.hash)throw g("invalid_request","Identity provider URLs must not include credentials, query params, or fragments.");Nu(t,e);let a=Lt(t.hostname);if(!r&&ju(a))throw g("invalid_request",`Blocked identity provider host: ${a}`);return t}o(gh,"validateIdentityProviderUrl");function yh(e,t){let r=new URL(e),n=r.protocol==="http:"&&xe(r)&&II();if(r.protocol!=="https:"&&!n||r.pathname==="/"||r.username||r.password||r.search||r.hash)throw g("invalid_request",`CIMD ${t} must be an HTTPS URL with a path and no credentials, query, or fragment.`);if(Nu(r,e),!n&&ju(r.hostname))throw g("invalid_request",`CIMD ${t} points at a blocked host.`);return r}o(yh,"validateCimdUrl");function Ai(e){return yh(e,"client_id")}o(Ai,"validateCimdClientMetadataUrl");function Sh(e){return yh(e,"jwks_uri")}o(Sh,"validateCimdClientJwksUrl");function vh(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(vh,"mergeAbortSignals");async function $I(e){try{await e.cancel()}catch{}}o($I,"cancelReader");async function Ei(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 $I(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(Ei,"readBoundedByteStream");var MI=2,zI=1024*1024,qI=1e4,NI=new Set([301,302,303,307,308]),jI=["authorization","proxy-authorization","cookie","cookie2"];function Du(e){return typeof e=="string"?e:e instanceof URL?e.toString():e.url}o(Du,"readRequestUrl");function jn(e,t){return t?.method!==void 0?t.method.toUpperCase():e instanceof Request?e.method.toUpperCase():"GET"}o(jn,"readRequestMethod");function DI(e,t,r){let n=e.headers.get("content-length");if(!n)return;let a=Number.parseInt(n,10);if(Number.isFinite(a)&&a>t)throw g(r,"Outbound response exceeded the maximum allowed size.")}o(DI,"assertContentLengthWithinLimit");async function HI(e,t,r){return DI(e,t,r),Ei(e.body,{maxBytes:t,createLimitError:o(()=>g(r,"Outbound response exceeded the maximum allowed size."),"createLimitError")})}o(HI,"readBoundedResponseBody");function LI(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(LI,"responseFromBufferedBody");function BI(e,t){if(!NI.has(e.status))return;let r=e.headers.get("location");if(r)return new URL(r,t).toString()}o(BI,"resolveRedirectUrl");function _h(e,t){try{return t.validateUrl(e)}catch(r){throw g(t.problemCode,"Outbound URL was not allowed.",r)}}o(_h,"validateOutboundUrl");function GI(e,t){throw ge(e)!==void 0?e:g(t,"Outbound fetch failed.",e)}o(GI,"normalizeFetchError");function Ho(e,t){if(e===void 0)return;let r={event:t.event,code:t.problemCode,method:t.method};if(t.host!==void 0&&(r.host=t.host),t.extra!==void 0)for(let[n,a]of Object.entries(t.extra))a!==void 0&&(r[n]=a);t.error!==void 0&&Ye(r,"error",t.error),e.log.warn(r,"Outbound HTTP exchange rejected")}o(Ho,"logOutboundFailure");async function VI(e,t,r,n,a,i,s){let c=jn(r,n);try{return await t(r,n)}catch(d){let p=d instanceof DOMException&&d.name==="AbortError";Ho(e,{event:p?"outbound_fetch_aborted":"outbound_fetch_failed",problemCode:a,method:c,host:lt(i),error:d,extra:{abortReason:s()}}),GI(d,a)}}o(VI,"fetchWithNormalizedError");function FI(e){if(e.redirects>=e.maxRedirects)throw g(e.problemCode,"Outbound redirects exceeded the maximum allowed depth.");if(e.method!=="GET"&&e.method!=="HEAD")throw g(e.problemCode,"Outbound redirect after a non-idempotent request was blocked.")}o(FI,"assertRedirectAllowed");function ZI(e,t){let r=new Headers(e);for(let n of jI)r.delete(n);for(let n of t)r.delete(n);return r}o(ZI,"stripCrossOriginHeaders");function KI(e,t,r,n,a){let i={...e,method:t,redirect:"manual",signal:r};return n&&(i.headers=ZI(e.headers,a)),i}o(KI,"buildRedirectInit");function JI(e,t,r){let n={...t,redirect:"manual",signal:r};return n.headers===void 0&&e instanceof Request&&(n.headers=e.headers),n}o(JI,"buildInitialRequestInit");function WI(e){let t=jn(e.currentInput,e.currentInit);FI({redirects:e.redirects,maxRedirects:e.maxRedirects,method:t,problemCode:e.problemCode});let r=_h(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:KI(e.currentInit,t,e.signal,a,e.additionalCrossOriginStrippedHeaders),redirects:e.redirects+1}}o(WI,"followRedirect");async function Hu(e,t,r){let n=r.problemCode??"invalid_request",a=r.maxRedirects??MI,i=r.maxResponseBytes??zI,s=r.timeoutMs??qI,c=r.fetchImpl??fetch,d=r.additionalCrossOriginStrippedHeaders??[],p=r.context,l=new AbortController,m=vh(l,t.signal),h=!1,y=setTimeout(()=>{h=!0,l.abort()},s),v=e,S=JI(e,t,l.signal),_;try{_=_h(Du(e),{problemCode:n,validateUrl:r.validateUrl}).toString()}catch(b){throw Ho(p,{event:"outbound_url_blocked",problemCode:n,method:jn(e,t),host:lt(Du(e)),error:b}),clearTimeout(y),m?.(),b}let w=0;try{for(;;){let b=await VI(p,c,v,S,n,_,()=>h?`timeout_after_${s}ms`:void 0),R=BI(b,_);if(R!==void 0)try{let z=WI({currentInput:v,currentInit:S,currentUrl:_,redirectUrl:R,redirects:w,maxRedirects:a,problemCode:n,validateUrl:r.validateUrl,signal:l.signal,additionalCrossOriginStrippedHeaders:d});v=z.currentInput,S=z.currentInit,_=z.currentUrl,w=z.redirects;continue}catch(z){throw Ho(p,{event:"outbound_redirect_blocked",problemCode:n,method:jn(v,S),host:lt(_),error:z,extra:{redirects:w,maxRedirects:a,redirectTargetHost:lt(R)}}),z}try{return LI(b,await HI(b,i,n))}catch(z){throw Ho(p,{event:"outbound_response_size_exceeded",problemCode:n,method:jn(v,S),host:lt(_),error:z,extra:{maxResponseBytes:i,status:b.status}}),z}}}finally{clearTimeout(y),m?.()}}o(Hu,"runSafeOutboundExchange");async function Ui(e,t,r){let n=await Hu(e,t,r);try{return{response:n,json:await n.clone().json()}}catch(a){throw Ho(r.context,{event:"outbound_json_parse_failed",problemCode:r.problemCode??"invalid_request",method:jn(e,t),host:lt(Du(e)),error:a,extra:{status:n.status,contentType:n.headers.get("content-type")??void 0}}),g(r.problemCode??"invalid_request","Outbound JSON response could not be parsed.",a)}}o(Ui,"runSafeOutboundJsonExchange");function Dn(e,t={},r={}){return Hu(e,t,{...r,validateUrl:hh})}o(Dn,"fetchConfiguredOutbound");function wh(e,t={},r={}){return Ui(e,t,{...r,validateUrl:gh})}o(wh,"fetchIdentityProviderJson");function bh(e,t={},r={}){return Ui(e,t,{...r,validateUrl:Ai})}o(bh,"fetchCimdClientMetadataJson");function Rh(e,t={},r={}){return Ui(e,t,{...r,validateUrl:Sh})}o(Rh,"fetchCimdClientJwksJson");var YI={"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 At(e){return YI[e]}o(At,"describeUpstreamAuthMode");function Oi(e){return At(e).ownerMode}o(Oi,"resolveOwnerModeForUpstreamAuthMode");ue();import{errors as Eh,jwtVerify as Uh,SignJWT as Oh}from"jose";var Qe="zuplo-mcp-gateway",it=Qe,st="HS256";import{base64url as QI}from"jose";var XI=new TextEncoder,eP="MCP gateway could not initialize secure key material.",tP=32,Ch=new Map,Ih=new Map,rP;function nP(){return rP??wo.instance.authPrivateKey}o(nP,"readAuthPrivateKey");function Ph(e){return new bn(eP,e===void 0?void 0:{cause:e})}o(Ph,"createGeneratedKeyMaterialError");function xh(e,t){let r=QI.decode(t);if(r.byteLength!==tP)throw new Error(`Generated deployment auth key ${e} is invalid.`);return r}o(xh,"decodeJwkKeyField");function oP(e){let t=nP();if(!t)throw Ph();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=xh("d",r.d);xh("x",r.x);let a=XI.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 Ph(r)}}o(oP,"decodeGeneratedKeyMaterial");function aP(e){let t=Ch.get(e);return t||(t=oP(e),Ch.set(e,t)),t}o(aP,"getMasterKeyMaterial");async function Et(e){let t=Ih.get(e.purpose);if(t!==void 0)return t;let r=await e.derive(aP(e.keyMaterialPurpose));return Ih.set(e.purpose,r),r}o(Et,"readCachedDerivedKey");var iP="SHA-256";var sP="zuplo-mcp-gateway:",cP=new TextEncoder,kh=new WeakMap;async function Sr(e,t){let r=kh.get(e);r||(r=new Map,kh.set(e,r));let n=r.get(t);if(n)return n;let a=await uP(e,t);return r.set(t,a),a}o(Sr,"deriveGatewaySigningKey");async function uP(e,t){let r=Th(e),n=await crypto.subtle.importKey("raw",r,{name:"HKDF"},!1,["deriveBits"]),a=cP.encode(`${sP}${t}`),i=await crypto.subtle.deriveBits({name:"HKDF",hash:iP,salt:new Uint8Array,info:Th(a)},n,32*8);return new Uint8Array(i)}o(uP,"hkdfExpand");function Th(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Th,"copyToArrayBuffer");var $h=15*60,dP=15*60,lP=Mm.extend({id:En}),pP=lP.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),Mh=Tn.extend({id:To,purpose:u.literal("browser_connect")}),mP=Tn.extend({purpose:u.literal("browser_connect")}),fP=Mh.extend({exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),zh=$h*1e3;async function qh(){return Et({purpose:"oauth-state",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Sr(e,"oauth-state"),"derive")})}o(qh,"getOAuthStateKey");async function Nh(){return Et({purpose:"browser-connect",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Sr(e,"browser-connect"),"derive")})}o(Nh,"getBrowserConnectKey");async function jh(e){let t=Math.floor(Date.now()/1e3)+$h;return new Oh(e).setProtectedHeader({alg:st,typ:"JWT"}).setIssuer(Qe).setAudience(it).setIssuedAt().setExpirationTime(t).sign(await qh())}o(jh,"signOAuthState");async function $i(e){try{let{payload:t}=await Uh(e,await qh(),{algorithms:[st],issuer:Qe,audience:it});return pP.parse(t)}catch(t){throw t instanceof Eh.JWTExpired?g("oauth_state_expired","OAuth state has expired",t):g("oauth_state_invalid","OAuth state could not be verified",t)}}o($i,"verifyOAuthState");async function Dh(e){let t=Math.floor(Date.now()/1e3)+dP,r=mP.parse(e),n=Mh.parse({...r,id:Dm()});return new Oh(n).setProtectedHeader({alg:st,typ:"JWT"}).setIssuer(Qe).setAudience(it).setIssuedAt().setExpirationTime(t).sign(await Nh())}o(Dh,"signBrowserConnectTicket");async function Mi(e){try{let{payload:t}=await Uh(e,await Nh(),{algorithms:[st],issuer:Qe,audience:it});return fP.parse(t)}catch(t){throw t instanceof Eh.JWTExpired?g("oauth_state_expired","Browser connect ticket has expired",t):g("oauth_state_invalid","Browser connect ticket could not be verified",t)}}o(Mi,"verifyBrowserConnectTicket");async function zi(e){if((await K().consumeBrowserConnectTicket({id:e.id,expiresAt:re(new Date(e.exp*1e3)),now:re(new Date)})).kind==="consumed")throw g("oauth_state_reused","Browser connect ticket has already been used")}o(zi,"consumeBrowserConnectTicket");function hP(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(hP,"buildConnectRequiredMessage");async function Hh(e){let t=ae(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 Dh({...ko(e),purpose:"browser_connect"})),r.toString()}o(Hh,"buildGatewayBrowserTicketUrl");function gP(e){return`/auth/connections/${encodeURIComponent(e)}/connect`}o(gP,"buildGatewayConnectPath");async function Lu(e){return Hh({...e,path:gP(e.upstreamServerId),redirect:!0})}o(Lu,"buildGatewayConnectUrl");async function Lh(e){return Hh({...e,path:`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`})}o(Lh,"buildGatewayAppPasswordCaptureUrl");async function vr(e){let t={requestUrl:e.requestUrl,owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}};return{state:e.requiresReconsent?"reconsent_required":"authenticating",upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.connectionId?{connectionId:e.connectionId}:{},authUrl:await Lu(t),message:hP(e.upstreamDisplayName,e.subject,e.requiresReconsent),nextAction:"redirect"}}o(vr,"buildRedirectConnectRequiredResponse");function qi(e){return Bh({...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(qi,"buildAdminConnectRequiredResponse");function Bh(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(Bh,"buildAdminSetupRequiredResponse");function Gh(e){return Bh({...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(Gh,"buildAdminStaticSecretRequiredResponse");ue();import{base64url as _r}from"jose";var yP="SHA-256",Ln="AES-GCM",SP=12,Gu="zuplo-secret",Vu=1,Vh="generated:auth_private_key:token-encryption",vP=u.object({version:u.literal(Vu),keyId:u.literal(Vh),algorithm:u.literal(Ln),iv:u.string().min(1),ciphertext:u.string().min(1)}).strict();function Hn(e){let t=new ArrayBuffer(e.byteLength);return new Uint8Array(t).set(e),t}o(Hn,"copyToArrayBuffer");async function Bu(){return Et({purpose:"token-encryption",keyMaterialPurpose:"token-encryption",derive:o(async e=>{let t=await crypto.subtle.digest(yP,Hn(e));return crypto.subtle.importKey("raw",t,{name:Ln},!1,["encrypt","decrypt"])},"derive")})}o(Bu,"getEncryptionKey");function Fh(e){return Hn(new TextEncoder().encode(`${Gu}:v${e.version}:${e.keyId}`))}o(Fh,"getAssociatedData");function _P(e){return`${Gu}:v${e.version}:${_r.encode(new TextEncoder().encode(JSON.stringify(e)))}`}o(_P,"encodeEnvelope");function wP(e){let t=`${Gu}:v${Vu}:`;if(!e.startsWith(t))return;let r=e.slice(t.length),n=new TextDecoder().decode(_r.decode(r));return vP.parse(JSON.parse(n))}o(wP,"decodeEnvelope");async function Zr(e){let t=await Bu(),r=crypto.getRandomValues(new Uint8Array(SP)),n={version:Vu,keyId:Vh},a=await crypto.subtle.encrypt({name:Ln,iv:r,additionalData:Fh(n)},t,new TextEncoder().encode(e));return _P({...n,algorithm:Ln,iv:_r.encode(r),ciphertext:_r.encode(new Uint8Array(a))})}o(Zr,"encryptSecret");async function Kt(e){let t=wP(e);if(t){let s=await Bu(),c=await crypto.subtle.decrypt({name:Ln,iv:Hn(_r.decode(t.iv)),additionalData:Fh(t)},s,Hn(_r.decode(t.ciphertext)));return new TextDecoder().decode(c)}let[r,n]=e.split(".");if(!r||!n)throw g("internal_server_error","Encrypted payload is malformed");let a=await Bu(),i=await crypto.subtle.decrypt({name:Ln,iv:Hn(_r.decode(r))},a,Hn(_r.decode(n)));return new TextDecoder().decode(i)}o(Kt,"decryptSecret");function bP(e,t){let r=yr({upstreamServerId:e,authProfileId:t});if(r.mode!=="shared-secret")throw g("invalid_request",`Upstream server ${e} does not use tenant static credentials.`);return r.secret}o(bP,"requireTenantStaticSecretConfig");function Zh(e){return e?.status==="active"&&e.metadata?.staticSecretKind==="bearer_token"&&!!e.metadata.encryptedStaticSecret}o(Zh,"hasUsableTenantStaticSecret");async function RP(e){if(!Zh(e.connection))throw g("internal_server_error","Stored tenant static credential is incomplete.");return{type:"bearer_token",token:await Kt(e.connection.metadata.encryptedStaticSecret)}}o(RP,"resolveTenantStaticSecretCredential");async function Kh(e){let t=De(e.upstreamServerId);bP(e.upstreamServerId,e.authProfileId);let r="preloadedConnection"in e?e.preloadedConnection:(await K().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(Zh(r))return{kind:"authorized",credential:await RP({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:Gh(n)}}o(Kh,"resolveTenantStaticSecretCredentialForRequest");ue();async function Fu(e){return K().upsertUpstreamConnection({id:ci(),ownerMode:e.owner.mode,subjectId:e.owner.mode==="user"?e.owner.subjectId:void 0,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,status:"active",encryptedAccessToken:void 0,encryptedRefreshToken:void 0,scopes:[],expiresAt:void 0,metadata:e.metadata})}o(Fu,"upsertStaticSecretConnection");var CP=u.string().trim().min(1).max(320),IP=u.string().min(1).max(4096),PP=u.string().trim().min(1).max(4096);function Zu(e,t){let r=yr({upstreamServerId:e,authProfileId:t});if(r.mode!=="user-secret")throw g("invalid_request",`Upstream server ${e} does not use user static credentials.`);return r.secret}o(Zu,"requireUserStaticSecretConfig");function xP(e){let t=new TextEncoder().encode(e),r="";for(let n of t)r+=String.fromCharCode(n);return btoa(r)}o(xP,"encodeBase64Utf8");function kP(e){return`Basic ${xP(`${e.username}:${e.appPassword}`)}`}o(kP,"buildBasicAuthHeader");function Jh(e){return e?.status==="active"&&!!e.metadata?.encryptedStaticSecret}o(Jh,"hasEncryptedUserStaticSecret");async function TP(e){if(!Jh(e.connection))throw g("internal_server_error","Stored user static credential is incomplete.");if(e.connection.metadata.staticSecretKind==="bearer_token")return{type:"bearer_token",token:await Kt(e.connection.metadata.encryptedStaticSecret)};if(e.connection.metadata.staticSecretKind==="basic_auth_app_password"&&e.connection.metadata.staticSecretUsername)return{type:"headers",headers:{Authorization:kP({username:e.connection.metadata.staticSecretUsername,appPassword:await Kt(e.connection.metadata.encryptedStaticSecret)})}};throw g("internal_server_error","Stored user static credential kind is unsupported.")}o(TP,"resolveUserStaticSecretCredential");async function Wh(e){if(Zu(e.upstreamServerId,e.authProfileId).kind!=="basic_auth_app_password")throw g("invalid_request","This upstream does not use username and app-password credentials.");if(e.owner.mode!=="user")throw g("invalid_request","User static credentials must be stored under a user-owned connection.");let r=CP.parse(e.username),n=IP.parse(e.appPassword);return Fu({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await Zr(n),staticSecretKind:"basic_auth_app_password",staticSecretUsername:r}})}o(Wh,"saveUserStaticSecretCredential");async function Ni(e){let t=Zu(e.upstreamServerId,e.authProfileId);if(t.kind!=="bearer_token")throw g("invalid_request","This upstream does not use bearer token credentials.");if(e.owner.mode!=="user")throw g("invalid_request","User static credentials must be stored under a user-owned connection.");let r=PP.parse(e.token);return Fu({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,metadata:{connectedBySubjectId:e.initiatedBySubjectId,encryptedStaticSecret:await Zr(r),staticSecretKind:t.kind,staticSecretLabel:t.label}})}o(Ni,"saveUserStaticBearerTokenCredential");function Ku(e,t){return Zu(e,t)}o(Ku,"readUserStaticSecretCaptureConfig");async function Yh(e){let t=De(e.upstreamServerId);if(e.owner.mode!=="user")throw g("internal_server_error","User static credential flow resolved a non-user owner.");let r="preloadedConnection"in e?e.preloadedConnection:(await K().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];if(Jh(r))return{kind:"authorized",credential:await TP({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 vr(n)}}o(Yh,"resolveUserStaticSecretCredentialForRequest");function Qh(e){if(e.owner.mode!=="user")throw g("invalid_request","User static credential capture requires a user-owned connection.");return Lh({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(Qh,"buildUserStaticSecretConnectUrl");var Ju;Ju=globalThis.crypto;async function AP(e){return(await Ju).getRandomValues(new Uint8Array(e))}o(AP,"getRandomValues");async function EP(e){let t="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~",r=Math.pow(2,8)-Math.pow(2,8)%t.length,n="";for(;n.length<e;){let a=await AP(e-n.length);for(let i of a)i<r&&(n+=t[i%t.length])}return n}o(EP,"random");async function UP(e){return await EP(e)}o(UP,"generateVerifier");async function OP(e){let t=await(await Ju).subtle.digest("SHA-256",new TextEncoder().encode(e));return btoa(String.fromCharCode(...new Uint8Array(t))).replace(/\//g,"_").replace(/\+/g,"-").replace(/=/g,"")}o(OP,"generateChallenge");async function Wu(e){if(e||(e=43),e<43||e>128)throw`Expected a length between 43 and 128. Received ${e}.`;let t=await UP(e),r=await OP(t);return{code_verifier:t,code_challenge:r}}o(Wu,"pkceChallenge");ue();var $e=Qp().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:rm.custom,message:"URL must be parseable",fatal:!0}),Wp}).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"}),ji=Ce({resource:f().url(),authorization_servers:C($e).optional(),jwks_uri:f().url().optional(),scopes_supported:C(f()).optional(),bearer_methods_supported:C(f()).optional(),resource_signing_alg_values_supported:C(f()).optional(),resource_name:f().optional(),resource_documentation:f().optional(),resource_policy_uri:f().url().optional(),resource_tos_uri:f().url().optional(),tls_client_certificate_bound_access_tokens:oe().optional(),authorization_details_types_supported:C(f()).optional(),dpop_signing_alg_values_supported:C(f()).optional(),dpop_bound_access_tokens_required:oe().optional()}),Lo=Ce({issuer:f(),authorization_endpoint:$e,token_endpoint:$e,registration_endpoint:$e.optional(),scopes_supported:C(f()).optional(),response_types_supported:C(f()),response_modes_supported:C(f()).optional(),grant_types_supported:C(f()).optional(),token_endpoint_auth_methods_supported:C(f()).optional(),token_endpoint_auth_signing_alg_values_supported:C(f()).optional(),service_documentation:$e.optional(),revocation_endpoint:$e.optional(),revocation_endpoint_auth_methods_supported:C(f()).optional(),revocation_endpoint_auth_signing_alg_values_supported:C(f()).optional(),introspection_endpoint:f().optional(),introspection_endpoint_auth_methods_supported:C(f()).optional(),introspection_endpoint_auth_signing_alg_values_supported:C(f()).optional(),code_challenge_methods_supported:C(f()).optional(),client_id_metadata_document_supported:oe().optional()}),$P=Ce({issuer:f(),authorization_endpoint:$e,token_endpoint:$e,userinfo_endpoint:$e.optional(),jwks_uri:$e,registration_endpoint:$e.optional(),scopes_supported:C(f()).optional(),response_types_supported:C(f()),response_modes_supported:C(f()).optional(),grant_types_supported:C(f()).optional(),acr_values_supported:C(f()).optional(),subject_types_supported:C(f()),id_token_signing_alg_values_supported:C(f()),id_token_encryption_alg_values_supported:C(f()).optional(),id_token_encryption_enc_values_supported:C(f()).optional(),userinfo_signing_alg_values_supported:C(f()).optional(),userinfo_encryption_alg_values_supported:C(f()).optional(),userinfo_encryption_enc_values_supported:C(f()).optional(),request_object_signing_alg_values_supported:C(f()).optional(),request_object_encryption_alg_values_supported:C(f()).optional(),request_object_encryption_enc_values_supported:C(f()).optional(),token_endpoint_auth_methods_supported:C(f()).optional(),token_endpoint_auth_signing_alg_values_supported:C(f()).optional(),display_values_supported:C(f()).optional(),claim_types_supported:C(f()).optional(),claims_supported:C(f()).optional(),service_documentation:f().optional(),claims_locales_supported:C(f()).optional(),ui_locales_supported:C(f()).optional(),claims_parameter_supported:oe().optional(),request_parameter_supported:oe().optional(),request_uri_parameter_supported:oe().optional(),require_request_uri_registration:oe().optional(),op_policy_uri:$e.optional(),op_tos_uri:$e.optional(),client_id_metadata_document_supported:oe().optional()}),Di=I({...$P.shape,...Lo.pick({code_challenge_methods_supported:!0}).shape}),Bo=I({access_token:f(),id_token:f().optional(),token_type:f(),expires_in:nm.number().optional(),scope:f().optional(),refresh_token:f().optional()}).strip(),eg=I({error:f(),error_description:f().optional(),error_uri:f().optional()}),Xh=$e.optional().or(U("").transform(()=>{})),MP=I({redirect_uris:C($e),token_endpoint_auth_method:f().optional(),grant_types:C(f()).optional(),response_types:C(f()).optional(),client_name:f().optional(),client_uri:$e.optional(),logo_uri:Xh,scope:f().optional(),contacts:C(f()).optional(),tos_uri:Xh,policy_uri:f().optional(),jwks_uri:$e.optional(),jwks:em().optional(),software_id:f().optional(),software_version:f().optional(),software_statement:f().optional()}).strip(),Yu=I({client_id:f(),client_secret:f().optional(),client_id_issued_at:X().optional(),client_secret_expires_at:X().optional()}).strip(),Go=MP.merge(Yu),eL=I({error:f(),error_description:f().optional()}).strip(),tL=I({token:f(),token_type_hint:f().optional()}).strip();function tg(e){let t=typeof e=="string"?new URL(e):new URL(e.href);return t.hash="",t}o(tg,"resourceUrlFromServerUrl");function rg({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(rg,"checkResourceAllowed");var be=class extends Error{static{o(this,"OAuthError")}constructor(t,r){super(t),this.errorUri=r,this.name=this.constructor.name}toResponseObject(){let t={error:this.errorCode,error_description:this.message};return this.errorUri&&(t.error_uri=this.errorUri),t}get errorCode(){return this.constructor.errorCode}},Vo=class extends be{static{o(this,"InvalidRequestError")}};Vo.errorCode="invalid_request";var Kr=class extends be{static{o(this,"InvalidClientError")}};Kr.errorCode="invalid_client";var Jr=class extends be{static{o(this,"InvalidGrantError")}};Jr.errorCode="invalid_grant";var Wr=class extends be{static{o(this,"UnauthorizedClientError")}};Wr.errorCode="unauthorized_client";var Fo=class extends be{static{o(this,"UnsupportedGrantTypeError")}};Fo.errorCode="unsupported_grant_type";var Zo=class extends be{static{o(this,"InvalidScopeError")}};Zo.errorCode="invalid_scope";var Ko=class extends be{static{o(this,"AccessDeniedError")}};Ko.errorCode="access_denied";var Jt=class extends be{static{o(this,"ServerError")}};Jt.errorCode="server_error";var Jo=class extends be{static{o(this,"TemporarilyUnavailableError")}};Jo.errorCode="temporarily_unavailable";var Wo=class extends be{static{o(this,"UnsupportedResponseTypeError")}};Wo.errorCode="unsupported_response_type";var Yo=class extends be{static{o(this,"UnsupportedTokenTypeError")}};Yo.errorCode="unsupported_token_type";var Qo=class extends be{static{o(this,"InvalidTokenError")}};Qo.errorCode="invalid_token";var Xo=class extends be{static{o(this,"MethodNotAllowedError")}};Xo.errorCode="method_not_allowed";var ea=class extends be{static{o(this,"TooManyRequestsError")}};ea.errorCode="too_many_requests";var Yr=class extends be{static{o(this,"InvalidClientMetadataError")}};Yr.errorCode="invalid_client_metadata";var ta=class extends be{static{o(this,"InsufficientScopeError")}};ta.errorCode="insufficient_scope";var ra=class extends be{static{o(this,"InvalidTargetError")}};ra.errorCode="invalid_target";var ng={[Vo.errorCode]:Vo,[Kr.errorCode]:Kr,[Jr.errorCode]:Jr,[Wr.errorCode]:Wr,[Fo.errorCode]:Fo,[Zo.errorCode]:Zo,[Ko.errorCode]:Ko,[Jt.errorCode]:Jt,[Jo.errorCode]:Jo,[Wo.errorCode]:Wo,[Yo.errorCode]:Yo,[Qo.errorCode]:Qo,[Xo.errorCode]:Xo,[ea.errorCode]:ea,[Yr.errorCode]:Yr,[ta.errorCode]:ta,[ra.errorCode]:ra};var wt=class extends Error{static{o(this,"UnauthorizedError")}constructor(t){super(t??"Unauthorized")}};function zP(e){return["client_secret_basic","client_secret_post","none"].includes(e)}o(zP,"isClientAuthMethod");var Qu="code",Xu="S256";function qP(e,t){let r=e.client_secret!==void 0;return"token_endpoint_auth_method"in e&&e.token_endpoint_auth_method&&zP(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(qP,"selectClientAuthMethod");function NP(e,t,r,n){let{client_id:a,client_secret:i}=t;switch(e){case"client_secret_basic":jP(a,i,r);return;case"client_secret_post":DP(a,i,n);return;case"none":HP(a,n);return;default:throw new Error(`Unsupported client authentication method: ${e}`)}}o(NP,"applyClientAuthentication");function jP(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(jP,"applyBasicAuth");function DP(e,t,r){r.set("client_id",e),t&&r.set("client_secret",t)}o(DP,"applyPostAuth");function HP(e,t){t.set("client_id",e)}o(HP,"applyPublicAuth");async function ag(e){let t=e instanceof Response?e.status:void 0,r=e instanceof Response?await e.text():e;try{let n=eg.parse(JSON.parse(r)),{error:a,error_description:i,error_uri:s}=n,c=ng[a]||Jt;return new c(i||"",s)}catch(n){let a=`${t?`HTTP ${t}: `:""}Invalid OAuth error response: ${n}. Raw body: ${r}`;return new Jt(a)}}o(ag,"parseErrorResponse");async function wr(e,t){try{return await ed(e,t)}catch(r){if(r instanceof Kr||r instanceof Wr)return await e.invalidateCredentials?.("all"),await ed(e,t);if(r instanceof Jr)return await e.invalidateCredentials?.("tokens"),await ed(e,t);throw r}}o(wr,"auth");async function ed(e,{serverUrl:t,authorizationCode:r,scope:n,resourceMetadataUrl:a,fetchFn:i}){let s=await e.discoveryState?.(),c,d,p,l=a;if(!l&&s?.resourceMetadataUrl&&(l=new URL(s.resourceMetadataUrl)),s?.authorizationServerUrl){if(d=s.authorizationServerUrl,c=s.resourceMetadata,p=s.authorizationServerMetadata??await sg(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 R=await ZP(t,{resourceMetadataUrl:l,fetchFn:i});d=R.authorizationServerUrl,p=R.authorizationServerMetadata,c=R.resourceMetadata,await e.saveDiscoveryState?.({authorizationServerUrl:String(d),resourceMetadataUrl:l?.toString(),resourceMetadata:c,authorizationServerMetadata:p})}let m=await LP(t,e,c),h=n||c?.scopes_supported?.join(" ")||e.clientMetadata.scope,y=await Promise.resolve(e.clientInformation());if(!y){if(r!==void 0)throw new Error("Existing OAuth client information is required when exchanging an authorization code");let R=p?.client_id_metadata_document_supported===!0,z=e.clientMetadataUrl;if(z&&!rd(z))throw new Yr(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${z}`);if(R&&z)y={client_id:z},await e.saveClientInformation?.(y);else{if(!e.saveClientInformation)throw new Error("OAuth client information must be saveable for dynamic registration");let je=await QP(d,{metadata:p,clientMetadata:e.clientMetadata,scope:h,fetchFn:i});await e.saveClientInformation(je),y=je}}let v=!e.redirectUrl;if(r!==void 0||v){let R=await YP(e,d,{metadata:p,resource:m,authorizationCode:r,fetchFn:i});return await e.saveTokens(R),"AUTHORIZED"}let S=await e.tokens();if(S?.refresh_token)try{let R=await WP(d,{metadata:p,clientInformation:y,refreshToken:S.refresh_token,resource:m,addClientAuthentication:e.addClientAuthentication,fetchFn:i});return await e.saveTokens(R),"AUTHORIZED"}catch(R){if(!(!(R instanceof be)||R instanceof Jt))throw R}let _=e.state?await e.state():void 0,{authorizationUrl:w,codeVerifier:b}=await KP(d,{metadata:p,clientInformation:y,state:_,redirectUrl:e.redirectUrl,scope:h,resource:m});return await e.saveCodeVerifier(b),await e.redirectToAuthorization(w),"REDIRECT"}o(ed,"authInternal");function rd(e){if(!e)return!1;try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(rd,"isHttpsUrl");async function LP(e,t,r){let n=tg(e);if(t.validateResourceURL)return await t.validateResourceURL(n,r?.resource);if(r){if(!rg({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(LP,"selectResourceURL");function nd(e){let t=e.headers.get("WWW-Authenticate");if(!t)return{};let[r,n]=t.split(" ");if(r.toLowerCase()!=="bearer"||!n)return{};let a=td(e,"resource_metadata")||void 0,i;if(a)try{i=new URL(a)}catch{}let s=td(e,"scope")||void 0,c=td(e,"error")||void 0;return{resourceMetadataUrl:i,scope:s,error:c}}o(nd,"extractWWWAuthenticateParams");function td(e,t){let r=e.headers.get("WWW-Authenticate");if(!r)return null;let n=new RegExp(`${t}=(?:"([^"]+)"|([^\\s,]+))`),a=r.match(n);return a?a[1]||a[2]:null}o(td,"extractFieldFromWwwAuth");async function ig(e,t,r=fetch){let n=await VP(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 ji.parse(await n.json())}o(ig,"discoverOAuthProtectedResourceMetadata");async function od(e,t,r=fetch){try{return await r(e,{headers:t})}catch(n){if(n instanceof TypeError)return t?od(e,void 0,r):void 0;throw n}}o(od,"fetchWithCorsRetry");function BP(e,t="",r={}){return t.endsWith("/")&&(t=t.slice(0,-1)),r.prependPathname?`${t}/.well-known/${e}`:`/.well-known/${e}${t}`}o(BP,"buildWellKnownPath");async function og(e,t,r=fetch){return await od(e,{"MCP-Protocol-Version":t},r)}o(og,"tryMetadataDiscovery");function GP(e,t){return!e||e.status>=400&&e.status<500&&t!=="/"}o(GP,"shouldAttemptFallback");async function VP(e,t,r,n){let a=new URL(e),i=n?.protocolVersion??pr,s;if(n?.metadataUrl)s=new URL(n.metadataUrl);else{let d=BP(t,a.pathname);s=new URL(d,n?.metadataServerUrl??a),s.search=a.search}let c=await og(s,i,r);if(!n?.metadataUrl&&GP(c,a.pathname)){let d=new URL(`/.well-known/${t}`,a);c=await og(d,i,r)}return c}o(VP,"discoverMetadataWithFallback");function FP(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(FP,"buildDiscoveryUrls");async function sg(e,{fetchFn:t=fetch,protocolVersion:r=pr}={}){let n={"MCP-Protocol-Version":r,Accept:"application/json"},a=FP(e);for(let{url:i,type:s}of a){let c=await od(i,n,t);if(c){if(!c.ok){if(await c.body?.cancel(),c.status>=400&&c.status<500)continue;throw new Error(`HTTP ${c.status} trying to load ${s==="oauth"?"OAuth":"OpenID provider"} metadata from ${i}`)}return s==="oauth"?Lo.parse(await c.json()):Di.parse(await c.json())}}}o(sg,"discoverAuthorizationServerMetadata");async function ZP(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 sg(n,{fetchFn:t?.fetchFn});return{authorizationServerUrl:n,authorizationServerMetadata:a,resourceMetadata:r}}o(ZP,"discoverOAuthServerInfo");async function KP(e,{metadata:t,clientInformation:r,redirectUrl:n,scope:a,state:i,resource:s}){let c;if(t){if(c=new URL(t.authorization_endpoint),!t.response_types_supported.includes(Qu))throw new Error(`Incompatible auth server: does not support response type ${Qu}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(Xu))throw new Error(`Incompatible auth server: does not support code challenge method ${Xu}`)}else c=new URL("/authorize",e);let d=await Wu(),p=d.code_verifier,l=d.code_challenge;return c.searchParams.set("response_type",Qu),c.searchParams.set("client_id",r.client_id),c.searchParams.set("code_challenge",l),c.searchParams.set("code_challenge_method",Xu),c.searchParams.set("redirect_uri",String(n)),i&&c.searchParams.set("state",i),a&&c.searchParams.set("scope",a),a?.includes("offline_access")&&c.searchParams.append("prompt","consent"),s&&c.searchParams.set("resource",s.href),{authorizationUrl:c,codeVerifier:p}}o(KP,"startAuthorization");function JP(e,t,r){return new URLSearchParams({grant_type:"authorization_code",code:e,code_verifier:t,redirect_uri:String(r)})}o(JP,"prepareAuthorizationCodeRequest");async function cg(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=qP(n,l);NP(m,n,d,r)}let p=await(s??fetch)(c,{method:"POST",headers:d,body:r});if(!p.ok)throw await ag(p);return Bo.parse(await p.json())}o(cg,"executeTokenRequest");async function WP(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 cg(e,{metadata:t,tokenRequestParams:c,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:s});return{refresh_token:n,...d}}o(WP,"refreshAuthorization");async function YP(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=JP(a,p,e.redirectUrl)}let d=await e.clientInformation();return cg(t,{metadata:r,tokenRequestParams:c,clientInformation:d??void 0,addClientAuthentication:e.addClientAuthentication,resource:n,fetchFn:i})}o(YP,"fetchToken");async function QP(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 ag(s);return Go.parse(await s.json())}o(QP,"registerClient");ue();function ad(e){return`Zuplo MCP Gateway - ${e}`}o(ad,"buildGatewayOAuthClientName");function ug(e,t){let r=new URL(e,ae(t));return xe(r)&&Lt(r.hostname)!=="localhost"&&(r.hostname="localhost"),r.toString()}o(ug,"buildGatewayOAuthRedirectUri");function id(e){let t=new URL(`/.well-known/oauth-client/${encodeURIComponent(e.upstreamServerId)}`,e.origin);return t.searchParams.set("authProfileId",e.authProfileId),t.toString()}o(id,"buildOAuthClientMetadataDocumentUrl");function dg(e){return ae(e)}o(dg,"requireOAuthClientMetadataOrigin");function lg(e,t,r){let n=De(t),a=Fr(t,r);return{client_id:id({origin:e,upstreamServerId:t,authProfileId:r}),client_name:ad(n.displayName),client_uri:new URL("/",e).toString(),redirect_uris:[new URL(a.redirectPath,e).toString()],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",token_endpoint_auth_method:"none"}}o(lg,"buildOAuthClientMetadataDocument");var XP=u.union([Go,Yu]),ex=u.object({authorizationServerUrl:u.url(),resourceMetadataUrl:u.url().optional(),resourceMetadata:ji.optional(),authorizationServerMetadata:u.union([Lo,Di]).optional()}).passthrough(),tx="Bearer";function rx(e){return e?e.split(/[,\s]+/).filter(Boolean):[]}o(rx,"splitScopes");function nx(e){return ti.parse(e)}o(nx,"parsePkceCodeVerifier");function ox(e){if(typeof e.expires_in=="number")return re(new Date(Date.now()+e.expires_in*1e3))}o(ox,"readTokenExpiry");async function pg(e){if(e!==void 0)return Zr(JSON.stringify(e))}o(pg,"encryptJson");async function mg(e,t){if(!e)return;let r=await Kt(e);try{return t.parse(JSON.parse(r))}catch(n){throw g("oauth_state_invalid","Stored upstream OAuth JSON state is invalid.",n)}}o(mg,"decryptJson");function ax(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(ax,"toOAuthDiscoveryState");function ix(e,t){return"redirect_uris"in e?e.redirect_uris.includes(t):!0}o(ix,"clientInformationAllowsRedirectUri");function sx(e,t,r){let n=De(e),a=Fr(e,t),i;return a.scopes.length>0&&(i=a.scopes.join(a.scopeDelimiter)),{client_name:ad(n.displayName),client_uri:new URL("/",new URL(r).origin).toString(),redirect_uris:[r],grant_types:["authorization_code","refresh_token"],response_types:["code"],application_type:"web",scope:i,token_endpoint_auth_method:"none"}}o(sx,"buildOAuthClientMetadata");function cx(e){let t;if(e.registration.tokenEndpointAuthMethod!=="none"&&(t=e.registration.clientSecret,!t))throw g("internal_server_error",`Manual OAuth registration for ${e.upstreamServerId} requires clientSecret.`);return Go.parse({...e.clientMetadata,client_id:e.registration.clientId,token_endpoint_auth_method:e.registration.tokenEndpointAuthMethod,...t===void 0?{}:{client_secret:t}})}o(cx,"buildManualOAuthClientInformation");function ux(e,t,r){let n=id({origin:new URL(r).origin,upstreamServerId:e,authProfileId:t});return rd(n)?n:void 0}o(ux,"buildClientMetadataUrl");function fg(e){for(let t of e)if(t!==void 0)return t}o(fg,"firstDefined");function dx(e){let t=Fr(e.target.upstreamServerId,e.target.authProfileId),r=sx(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);if(t.clientRegistration.mode==="manual")return{clientMetadata:r,configuredClientInformation:cx({clientMetadata:r,registration:t.clientRegistration,upstreamServerId:e.target.upstreamServerId})};let n=ux(e.target.upstreamServerId,e.target.authProfileId,e.redirectUri);return n===void 0?{clientMetadata:r}:{clientMetadata:r,clientMetadataUrl:n}}o(dx,"buildInitialOAuthClientSetup");function lx(e,t){if(t===void 0)return fg([e.pendingState?.encryptedClientInformation,e.connectionMetadata?.encryptedClientInformation,e.connection?.metadata?.encryptedClientInformation])}o(lx,"readEncryptedClientInformation");function px(e){return fg([e.pendingState?.encryptedDiscoveryState,e.connectionMetadata?.encryptedDiscoveryState,e.connection?.metadata?.encryptedDiscoveryState])}o(px,"readEncryptedDiscoveryState");var Qr=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=lx(t,this.configuredClientInformation),this.encryptedDiscoveryState=px(t)}get authorizationUrl(){return this.authorizationUrlValue}get redirectUrl(){return this.redirectUriValue}get clientMetadata(){return this.clientMetadataValue}async state(){let t=await this.createPendingState();return jh({id:t.id,...ko({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 pg(t),await this.syncPendingState(!1))}async discoveryState(){return this.loadPersistedDiscoveryState()}async saveDiscoveryState(t){this.cachedDiscoveryState=t,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=await pg(t),await this.syncPendingState(!1)}async tokens(){return this.loadStoredTokens()}async saveTokens(t){let r=Bo.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??ci(),ownerMode:this.target.owner.mode,subjectId:n,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,status:"active",encryptedAccessToken:await Zr(r.access_token),encryptedRefreshToken:r.refresh_token?await Zr(r.refresh_token):void 0,scopes:rx(r.scope??this.clientMetadataValue.scope),expiresAt:ox(r),metadata:this.readStoredOAuthPersistence(this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0)};this.connection=await K().upsertUpstreamConnection(a)}async redirectToAuthorization(t){this.authorizationUrlValue=t.toString()}async saveCodeVerifier(t){let r=await this.createPendingState();await this.persistPendingState({...r,codeVerifier:nx(t)})}async codeVerifier(){if(!this.pendingState?.codeVerifier)throw g("oauth_state_invalid","OAuth code verifier is missing");return this.pendingState.codeVerifier}async invalidateCredentials(t){let r=t==="all"||t==="client"||t==="tokens",n=t==="all"||t==="client",a=t==="all"||t==="discovery",i=t==="all"||t==="verifier";n&&(this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,this.encryptedClientInformation=void 0),a&&(this.cachedDiscoveryState=void 0,this.discoveryStateLoaded=!0,this.encryptedDiscoveryState=void 0),r&&(this.cachedTokens=void 0,this.tokensLoaded=!0),await this.syncPendingState(i),await this.persistCredentialInvalidation(r)}async createPendingState(){if(this.pendingState)return this.pendingState;let t={id:jm(),...ko({owner:this.target.owner,initiatedBySubjectId:this.target.initiatedBySubjectId,upstreamServerId:this.target.upstreamServerId,authProfileId:this.target.authProfileId,virtualServerId:this.target.virtualServerId,...this.target.returnTo===void 0?{}:{returnTo:this.target.returnTo}}),callbackPath:new URL(this.redirectUriValue).pathname,expiresAt:re(new Date(Date.now()+zh)),redirectUri:this.redirectUriValue,...this.returnOrigin===void 0?{}:{returnOrigin:this.returnOrigin},encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:this.target.owner.mode==="shared"?this.target.initiatedBySubjectId:void 0};return await this.persistPendingState(t),t}async persistPendingState(t){await K().saveUpstreamOAuthState({record:t}),this.pendingState=t}async syncPendingState(t){this.pendingState&&await this.persistPendingState({...this.pendingState,codeVerifier:t?void 0:this.pendingState.codeVerifier,encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState})}async loadPersistedClientInformation(){if(this.clientInformationLoaded)return this.cachedClientInformation;let t;try{t=await mg(this.encryptedClientInformation,XP)}catch{this.encryptedClientInformation=void 0,this.cachedClientInformation=void 0,this.clientInformationLoaded=!0,await this.syncPendingState(!1),await this.persistCredentialInvalidation(!1);return}if(t&&!ix(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=ax(await mg(this.encryptedDiscoveryState,ex))}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=Bo.parse({access_token:await Kt(this.connection.encryptedAccessToken),token_type:tx,refresh_token:this.connection.encryptedRefreshToken?await Kt(this.connection.encryptedRefreshToken):void 0,scope:this.connection.scopes.length>0?this.connection.scopes.join(" "):void 0});return this.cachedTokens=t,t}async persistCredentialInvalidation(t){if(!this.connection)return;let r={id:this.connection.id,ownerMode:this.connection.ownerMode,subjectId:this.connection.subjectId,upstreamServerId:this.connection.upstreamServerId,authProfileId:this.connection.authProfileId,status:this.connection.status,encryptedAccessToken:this.connection.encryptedAccessToken,encryptedRefreshToken:this.connection.encryptedRefreshToken,scopes:[...this.connection.scopes],expiresAt:this.connection.expiresAt,metadata:this.connection.metadata?{...this.connection.metadata}:void 0};t&&(r.status="reconsent_required",r.encryptedAccessToken=void 0,r.encryptedRefreshToken=void 0,r.scopes=[],r.expiresAt=void 0),r.metadata=this.readStoredOAuthPersistence(this.connection.metadata?.connectedBySubjectId),this.connection=await K().upsertUpstreamConnection(r)}readStoredOAuthPersistence(t){if(!(!this.encryptedClientInformation&&!this.encryptedDiscoveryState&&!t))return{encryptedClientInformation:this.encryptedClientInformation,encryptedDiscoveryState:this.encryptedDiscoveryState,connectedBySubjectId:t}}};var mx=3e4,fx=256*1024,hx=2;function gx(e){return!e||e.status!=="active"||!e.encryptedAccessToken?!1:e.expiresAt?new Date(e.expiresAt).getTime()>Date.now():!0}o(gx,"hasUsableAccessToken");var yx="does not support dynamic client registration";function Sx(e){return e instanceof Error&&e.message.includes(yx)}o(Sx,"isDynamicClientRegistrationUnsupported");function vx(e){return typeof e=="string"||e instanceof URL?{url:new URL(e.toString())}:{method:e.method,url:new URL(e.url)}}o(vx,"readOAuthFetchRequest");function _x(e,t){return(e.headers.get("content-type")??"").includes("json")||t.trimStart().startsWith("{")||t.trimStart().startsWith("[")}o(_x,"responseLooksJson");function hg(e){return async(t,r)=>{let n=vx(t),a=await Dn(t,r,{maxRedirects:hx,maxResponseBytes:fx,problemCode:"upstream_token_exchange_failed",timeoutMs:mx}),i=await a.clone().text();if(!_x(a,i))return a;try{JSON.parse(i)}catch(s){throw g("upstream_token_exchange_failed",`Upstream OAuth fetch ${n.url.origin}${n.url.pathname} for ${e} returned invalid JSON.`,s)}return a}}o(hg,"createUpstreamOAuthFetch");async function gg(e,t){try{return await wr(e,{serverUrl:t.serverUrl,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:hg(t.upstreamServerId)})}catch(r){throw Sx(r)?g("upstream_client_registration_required",`The authorization server for ${t.upstreamServerId} does not advertise Client ID Metadata Document support and does not support Dynamic Client Registration. Register a client for the gateway manually before retrying.`,r):r}}o(gg,"runUpstreamOAuth");async function wx(e,t){return wr(e,{serverUrl:t.serverUrl,authorizationCode:t.authorizationCode,resourceMetadataUrl:new URL(t.resourceMetadataUrl),fetchFn:hg(t.upstreamServerId)})}o(wx,"exchangeUpstreamAuthorizationCode");async function yg(e,t){let r=await gg(e,t);if(r==="REDIRECT"&&e.authorizationUrl)return e.authorizationUrl;throw r==="AUTHORIZED"?g("upstream_token_exchange_failed",`OAuth connect flow reused existing credentials instead of producing a redirect for ${t.upstreamServerId}`):g("upstream_token_exchange_failed",`Unexpected OAuth result for ${t.upstreamServerId}: ${r}`)}o(yg,"requireUpstreamAuthorizationRedirect");async function Sg(e){if(gx(e.connection))return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};let t=await gg(e.provider,{upstreamServerId:e.target.upstreamServerId,serverUrl:e.serverUrl,resourceMetadataUrl:e.resourceMetadataUrl});if(t==="AUTHORIZED")return{kind:"authorized",credential:{type:"mcp_oauth_provider",provider:e.provider}};if(t!=="REDIRECT")throw g("upstream_token_exchange_failed",`Unexpected OAuth result for ${e.target.upstreamServerId}: ${t}`);if(!e.provider.authorizationUrl)throw g("upstream_token_exchange_failed",`OAuth connect-required flow did not produce a redirect for ${e.target.upstreamServerId}`);return{kind:"connect_required",payload:await Px({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(Sg,"authorizeUpstreamOAuthSession");async function bx(e){let t=await $i(e.stateToken),r=await K().consumeUpstreamOAuthState({id:t.id,now:re(new Date)}),n=Rx(r);return Cx({storedState:n,signedState:t,upstreamServerId:e.upstreamServerId,callbackPath:new URL(e.request.url).pathname}),Ix(n),n}o(bx,"consumeStoredCallbackState");function Rx(e){switch(e.kind){case"consumed":throw g("oauth_state_reused","OAuth state has already been used");case"missing":throw g("oauth_state_expired","OAuth state is missing or expired");case"available":return e.record}}o(Rx,"readConsumedCallbackState");function Cx(e){if(![e.storedState.ownerMode===e.signedState.ownerMode,e.storedState.initiatedBySubjectId===e.signedState.initiatedBySubjectId,e.storedState.ownerSubjectId===e.signedState.ownerSubjectId,e.storedState.upstreamServerId===e.signedState.upstreamServerId,e.storedState.authProfileId===e.signedState.authProfileId,e.storedState.virtualServerId===e.signedState.virtualServerId,e.storedState.upstreamServerId===e.upstreamServerId,e.storedState.callbackPath===e.callbackPath].every(Boolean))throw g("oauth_callback_mismatch","OAuth callback did not match the initiating request")}o(Cx,"assertStoredCallbackStateMatches");function Ix(e){if(new Date(e.expiresAt).getTime()<=Date.now())throw g("oauth_state_expired","OAuth state has expired")}o(Ix,"assertStoredCallbackStateFresh");async function Px(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),qi(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),vr(t)}o(Px,"buildOAuthConnectRequiredResponse");async function vg(e){let t=await bx({request:e.request,upstreamServerId:e.upstreamServerId,stateToken:e.stateToken}),r=An(t),[n]=await K().batchGetUpstreamConnections([{owner:r,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId}]),a={target:{owner:r,initiatedBySubjectId:t.initiatedBySubjectId,upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId,virtualServerId:t.virtualServerId,...t.returnTo===void 0?{}:{returnTo:t.returnTo}},redirectUri:t.redirectUri,pendingState:t};n!==void 0&&(a.connection=n);let i=new Qr(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"?g("upstream_token_exchange_failed",`Unexpected OAuth result for ${e.upstreamServerId}: ${s}`):g("upstream_token_exchange_failed",`OAuth callback flow did not finish authorization for ${e.upstreamServerId}`)}o(vg,"finishUpstreamOAuthCallback");async function _g(e){let t=De(e.upstreamServerId),r=Fr(e.upstreamServerId,e.authProfileId),n=ug(r.redirectPath,e.request.url),a="preloadedConnection"in e?e.preloadedConnection:(await K().batchGetUpstreamConnections([{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}]))[0];return{upstreamServerConfig:t,connection:a,providerInput:{target:{owner:e.owner,initiatedBySubjectId:e.initiatedBySubjectId,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId,virtualServerId:e.virtualServerId,...e.returnTo===void 0?{}:{returnTo:e.returnTo}},redirectUri:n,returnOrigin:ae(e.request.url)}}}o(_g,"prepareUpstreamOAuthRequest");async function wg(e){let t=await _g(e),r=new Qr({...t.providerInput,...t.connection?.metadata===void 0?{}:{connectionMetadata:t.connection.metadata}});return yg(r,{upstreamServerId:e.upstreamServerId,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(wg,"startUpstreamConnect");async function bg(e){let t=await _g(e),r=new Qr({...t.providerInput,...t.connection===void 0?{}:{connection:t.connection}});return Sg({target:e,provider:r,connection:t.connection,upstreamDisplayName:t.upstreamServerConfig.displayName,serverUrl:t.upstreamServerConfig.transport.baseUrl,resourceMetadataUrl:t.upstreamServerConfig.transport.resourceMetadataUrl})}o(bg,"authorizeUpstreamRequest");function xx(e,t){switch(e.kind){case"bearer_token":{if(!e.token)throw g("internal_server_error",`Static bearer token is not configured for upstream ${t}.`);return{type:"bearer_token",token:e.token}}case"headers":{let r={};for(let n of e.headers){if(!n.value)throw g("internal_server_error",`Static header ${n.name} is not configured for upstream ${t}.`);r[n.name]=n.value}return{type:"headers",headers:r}}}}o(xx,"resolveStaticSecretCredential");async function Hi(e){let{routeAuth:t}=e;switch(t.authMode){case"shared-oauth":case"user-oauth":return bg({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 Kh({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=yr({upstreamServerId:t.upstreamServerId,authProfileId:t.authProfileId});if(n.mode!=="static-secret")throw g("internal_server_error",`Resolved static-secret credential context loaded ${n.mode} config.`);return{kind:"authorized",credential:xx(n.secret,t.upstreamServerId)}}case"user-secret":return Yh({request:e.request,owner:t.owner,initiatedBySubjectId:t.initiatedBySubjectId,authProfileId:t.authProfileId,upstreamServerId:t.upstreamServerId,virtualServerId:t.virtualServerId,..."preloadedConnection"in e?{preloadedConnection:e.preloadedConnection}:{}})}throw g("internal_server_error",`Unsupported upstream auth route context ${JSON.stringify(t)}.`)}o(Hi,"resolveUpstreamCredentialForRoute");async function Rg(e){let t=dr(e.principal.subjectId),r=at().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 Ni({owner:t,initiatedBySubjectId:e.principal.subjectId,upstreamServerId:n.upstreamServerId,authProfileId:n.authProfileId,token:e.apiKey})}o(Rg,"saveBrowserLoginApiKeyCredentialsForVirtualServer");async function Cg(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=At(e.connectRequest.authMode);switch(n.connectSupport){case"oauth_authorization":t=await wg(r);break;case"user_secret_capture":t=await Qh(r);break;case"none":throw g("invalid_request",n.connectUnsupportedDetail??`Upstream server ${e.connectRequest.upstreamServerId} does not support browser connection flows.`)}return{authProfileId:e.connectRequest.authProfileId,authUrl:t,initiatedBySubjectId:e.connectRequest.initiatedBySubjectId,owner:e.connectRequest.owner,upstreamDisplayName:e.connectRequest.upstreamDisplayName,virtualServerId:e.connectRequest.virtualServerId}}o(Cg,"startUpstreamConnectForRequest");async function Ig(e){let r=(await $i(e.callbackRequest.state)).authProfileId,n=yr({upstreamServerId:e.callbackRequest.upstreamServerId,authProfileId:r});if(At(n.mode).callbackSupport!=="authorization_code")throw g("invalid_request",`Upstream server ${e.callbackRequest.upstreamServerId} does not support OAuth callbacks.`);return vg({request:e.request,upstreamServerId:e.callbackRequest.upstreamServerId,authorizationCode:e.callbackRequest.code,stateToken:e.callbackRequest.state,upstreamServerConfig:De(e.callbackRequest.upstreamServerId)})}o(Ig,"finishUpstreamCallbackForRequest");var sd=new kt("route-upstream-bindings");function Pg(e){return`${e.upstreamServerId}:${e.authProfileId}`}o(Pg,"buildRouteBindingDuplicateKey");function cd(e,t){let r=sd.get(e)??[],n=Pg(t);if(r.find(i=>Pg(i)===n)!==void 0)throw g("internal_server_error",`Route declares duplicate upstream binding ${t.upstreamServerId} + ${t.authProfileId}.`);r.push(t),sd.set(e,r)}o(cd,"appendResolvedUpstreamBindingContext");function Li(e){return sd.get(e)??[]}o(Li,"readResolvedUpstreamBindingContexts");var kx=new Set(["authorization","connection","content-length","cookie","cookie2","host","keep-alive","proxy-authenticate","proxy-authorization","te","trailer","transfer-encoding","upgrade"]),Tx=3e4,Ax=2*1024*1024,Ex=2;function Ux(e){return e.kind!=="authorized"||e.credential.type!=="headers"?[]:Object.keys(e.credential.headers)}o(Ux,"readCredentialHeaderNames");async function Ox(e,t){xt("handler.mcp-upstream");let r=Li(t);if(r.length!==1)throw new de(`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 Hi({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=De(n.upstreamServerId),s=i.transport.baseUrl,c=new Headers;for(let[h,y]of e.headers.entries())kx.has(h.toLowerCase())||c.set(h,y);let d=[];for(let h of i.transport.requestHeaders??[]){if(h.value===void 0){if(h.required)throw new de(`mcpUpstreamHandler: configured request header '${h.name}' is required but its value is unset. Set the env var that backs the header or mark the header optional.`);continue}c.set(h.name,h.value),d.push(h.name)}let p=a.credential;switch(p.type){case"bearer_token":c.set("authorization",`Bearer ${p.token}`);break;case"headers":for(let[h,y]of Object.entries(p.headers))c.set(h,y);break;case"mcp_oauth_provider":{let h=await p.provider.tokens();if(!h)return t.log.warn({event:"mcp_upstream_no_tokens",upstreamServerId:n.upstreamServerId},"MCP upstream proxy: OAuth provider returned no tokens"),Response.json({error:"no_upstream_tokens"},{status:401});c.set("authorization",`${h.token_type??"Bearer"} ${h.access_token}`);break}}let l=[...d,...Ux(a)],m={method:e.method,headers:c,body:e.method==="GET"||e.method==="HEAD"?void 0:e.body,duplex:"half"};return t.log.info({event:"mcp_upstream_handler_proxy",upstreamServerId:n.upstreamServerId,upstreamUrl:s,method:e.method},"MCP upstream proxy: forwarding request"),Dn(s,m,{additionalCrossOriginStrippedHeaders:l,context:t,maxRedirects:Ex,maxResponseBytes:Ax,problemCode:"upstream_capability_invocation_failed",timeoutMs:Tx})}o(Ox,"mcpUpstreamHandler");Uw();function br(e){return!!e._zod}o(br,"isZ4Schema");function Ge(e,t){return br(e)?dc(e,t):e.safeParse(t)}o(Ge,"safeParse");function Bn(e){if(!e)return;let t;if(br(e)?t=e._zod?.def?.shape:t=e.shape,!!t){if(typeof t=="function")try{return t()}catch{return}return t}}o(Bn,"getObjectShape");function xg(e){if(br(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(xg,"getLiteralValue");function Rr(e){return e==="completed"||e==="failed"||e==="cancelled"}o(Rr,"isTerminal");var Mx=Symbol("Let zodToJsonSchema decide on which parser to use");var P2=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function ud(e){let r=Bn(e)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=xg(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}o(ud,"getMethodLiteral");function dd(e,t){let r=Ge(e,t);if(!r.success)throw r.error;return r.data}o(dd,"parseWithCompat");var Hx=6e4,Gn=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(fi,r=>{this._oncancel(r)}),this.setNotificationHandler(Si,r=>{this._onprogress(r)}),this.setRequestHandler(yi,r=>({})),this._taskStore=t?.taskStore,this._taskMessageQueue=t?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(vi,async(r,n)=>{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new x(A.InvalidParams,"Failed to retrieve task: Task not found");return{...a}}),this.setRequestHandler(wi,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 x(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 x(A.InvalidParams,`Task not found: ${i}`);if(!Rr(s.status))return await this._waitForTaskUpdate(i,n.signal),await a();if(Rr(s.status)){let c=await this._taskStore.getTaskResult(i,n.sessionId);return this._clearTaskQueue(i),{...c,_meta:{...c._meta,[fr]:{taskId:i}}}}return await a()},"handleTaskResult");return await a()}),this.setRequestHandler(bi,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 x(A.InvalidParams,`Failed to list tasks: ${a instanceof Error?a.message:String(a)}`)}}),this.setRequestHandler(Ci,async(r,n)=>{try{let a=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!a)throw new x(A.InvalidParams,`Task not found: ${r.params.taskId}`);if(Rr(a.status))throw new x(A.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 x(A.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...i}}catch(a){throw a instanceof x?a:new x(A.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),x.fromError(A.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),_t(i)||Mn(i)?this._onresponse(i):Tt(i)?this._onrequest(i,s):Vf(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=x.fromError(A.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?.[fr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:t.id,error:{code:A.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=Lf(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 x(A.ConnectionClosed,"Request was cancelled");let y={...h,relatedRequestId:t.id};i&&!y.relatedTask&&(y.relatedTask={taskId:i});let v=y.relatedTask?.taskId??i;return v&&d&&await d.updateTaskStatus(v,"input_required"),await this.request(l,m,y)},"sendRequest"),authInfo:r?.authInfo,requestId:t.id,requestInfo:r?.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:c?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{c&&this.assertTaskHandlerCapability(t.method)}).then(()=>n(t,p)).then(async l=>{if(s.signal.aborted)return;let m={result:l,jsonrpc:"2.0",id:t.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:"response",message:m,timestamp:Date.now()},a?.sessionId):await a?.send(m)},async l=>{if(s.signal.aborted)return;let m={jsonrpc:"2.0",id:t.id,error:{code:Number.isSafeInteger(l.code)?l.code:A.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),_t(t))n(t);else{let s=new x(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(_t(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),_t(t))a(t);else{let s=x.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 x?s:new x(A.InternalError,String(s))}}return}let i;try{let s=await this.request(t,Zt,n);if(s.task)i=s.task.taskId,yield{type:"taskCreated",task:s.task};else throw new x(A.InternalError,"Task creation did not return a task");for(;;){let c=await this.getTask({taskId:i},n);if(yield{type:"taskStatus",task:c},Rr(c.status)){c.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:i},r,n)}:c.status==="failed"?yield{type:"error",error:new x(A.InternalError,`Task ${i} failed`)}:c.status==="cancelled"&&(yield{type:"error",error:new x(A.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 x?s:new x(A.InternalError,String(s))}}}request(t,r,n){let{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s,task:c,relatedTask:d}=n??{};return new Promise((p,l)=>{let m=o(b=>{l(b)},"earlyReject");if(!this._transport){m(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(t.method),c&&this.assertTaskCapability(t.method)}catch(b){m(b);return}n?.signal?.throwIfAborted();let h=this._requestMessageId++,y={...t,jsonrpc:"2.0",id:h};n?.onprogress&&(this._progressHandlers.set(h,n.onprogress),y.params={...t.params,_meta:{...t.params?._meta||{},progressToken:h}}),c&&(y.params={...y.params,task:c}),d&&(y.params={...y.params,_meta:{...y.params?._meta||{},[fr]:d}});let v=o(b=>{this._responseHandlers.delete(h),this._progressHandlers.delete(h),this._cleanupTimeout(h),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:h,reason:String(b)}},{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(z=>this._onerror(new Error(`Failed to send cancellation: ${z}`)));let R=b instanceof x?b:new x(A.RequestTimeout,String(b));l(R)},"cancel");this._responseHandlers.set(h,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return l(b);try{let R=Ge(r,b.result);R.success?p(R.data):l(R.error)}catch(R){l(R)}}}),n?.signal?.addEventListener("abort",()=>{v(n?.signal?.reason)});let S=n?.timeout??Hx,_=o(()=>v(x.fromError(A.RequestTimeout,"Request timed out",{timeout:S})),"timeoutHandler");this._setupTimeout(h,S,n?.maxTotalTimeout,_,n?.resetTimeoutOnProgress??!1);let w=d?.taskId;if(w){let b=o(R=>{let z=this._responseHandlers.get(h);z?z(R):this._onerror(new Error(`Response handler missing for side-channeled request ${h}`))},"responseResolver");this._requestResolvers.set(h,b),this._enqueueTaskMessage(w,{type:"request",message:y,timestamp:Date.now()}).catch(R=>{this._cleanupTimeout(h),l(R)})}else this._transport.send(y,{relatedRequestId:a,resumptionToken:i,onresumptiontoken:s}).catch(b=>{this._cleanupTimeout(h),l(b)})})}async getTask(t,r){return this.request({method:"tasks/get",params:t},_i,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},Ri,r)}async cancelTask(t,r){return this.request({method:"tasks/cancel",params:t},Zf,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||{},[fr]: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||{},[fr]: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||{},[fr]:r.relatedTask}}}),await this._transport.send(s,r)}setRequestHandler(t,r){let n=ud(t);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(a,i)=>{let s=dd(t,a);return Promise.resolve(r(s,i))})}removeRequestHandler(t){this._requestHandlers.delete(t)}assertCanSetRequestHandler(t){if(this._requestHandlers.has(t))throw new Error(`A request handler for ${t} already exists, which would be overridden`)}setNotificationHandler(t,r){let n=ud(t);this._notificationHandlers.set(n,a=>{let i=dd(t,a);return Promise.resolve(r(i))})}removeNotificationHandler(t){this._notificationHandlers.delete(t)}_cleanupTaskProgressHandler(t){let r=this._taskProgressTokens.get(t);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(t))}async _enqueueTaskMessage(t,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let a=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(t,r,n,a)}async _clearTaskQueue(t,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(t,r);for(let a of n)if(a.type==="request"&&Tt(a.message)){let i=a.message.id,s=this._requestResolvers.get(i);s?(s(new x(A.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 x(A.InvalidRequest,"Request cancelled"));return}let s=setTimeout(a,n);r.addEventListener("abort",()=>{clearTimeout(s),i(new x(A.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 x(A.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=zo.parse({method:"notifications/tasks/status",params:c});await this.notification(d),Rr(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 x(A.InvalidParams,`Task "${a}" not found - it may have been cleaned up`);if(Rr(c.status))throw new x(A.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=zo.parse({method:"notifications/tasks/status",params:d});await this.notification(p),Rr(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 Bi(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(Bi,"mergeCapabilities");var fv=Zp(Jl(),1),hv=Zp(mv(),1);function EU(){let e=new fv.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,hv.default)(e),e}o(EU,"createDefaultAjvInstance");var so=class{static{o(this,"AjvJsonSchemaValidator")}constructor(t){this._ajv=t??EU()}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 Ps=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},Gr,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},gr,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 xs(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(xs,"assertToolsCallTaskCapability");function ks(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(ks,"assertClientRequestTaskCapability");var Ts=class extends Gn{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(hi,n=>this._oninitialize(n)),this.setNotificationHandler(gi,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Cu,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 Ps(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=Bi(this._capabilities,t)}setRequestHandler(t,r){let a=Bn(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if(br(a)){let c=a;i=c._zod?.def?.value??c.value}else{let c=a;i=c._def?.value??c.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");if(i==="tools/call"){let c=o(async(d,p)=>{let l=Ge(No,d);if(!l.success){let v=l.error instanceof Error?l.error.message:String(l.error);throw new x(A.InvalidParams,`Invalid tools/call request: ${v}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let v=Ge(Zt,h);if(!v.success){let S=v.error instanceof Error?v.error.message:String(v.error);throw new x(A.InvalidParams,`Invalid task creation result: ${S}`)}return v.data}let y=Ge(hr,h);if(!y.success){let v=y.error instanceof Error?y.error.message:String(y.error);throw new x(A.InvalidParams,`Invalid tools/call result: ${v}`)}return y.data},"wrappedHandler");return super.setRequestHandler(t,c)}return super.setRequestHandler(t,r)}assertCapabilityForMethod(t){switch(t){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${t})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${t})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${t})`);break;case"ping":break}}assertNotificationCapability(t){switch(t){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${t})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${t})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${t})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${t})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(t){if(this._capabilities)switch(t){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${t})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${t})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${t})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${t})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${t})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${t})`);break;case"ping":case"initialize":break}}assertTaskCapability(t){ks(this._clientCapabilities?.tasks?.requests,t,"Client")}assertTaskHandlerCapability(t){this._capabilities&&xs(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:mr.includes(r)?r:pr,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"},Ft)}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},Do,r):this.request({method:"sampling/createMessage",params:t},Gr,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},gr,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},gr,r);if(i.action==="accept"&&i.content&&a.requestedSchema)try{let c=this._jsonSchemaValidator.getValidator(a.requestedSchema)(i.content);if(!c.valid)throw new x(A.InvalidParams,`Elicitation response content does not match requested schema: ${c.errorMessage}`)}catch(s){throw s instanceof x?s:new x(A.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},ku,r)}async sendLoggingMessage(t,r){if(this._capabilities.logging&&!this.isMessageIgnored(t.level,r))return this.notification({method:"notifications/message",params:t})}async sendResourceUpdated(t){return this.notification({method:"notifications/resources/updated",params:t})}async sendResourceListChanged(){return this.notification({method:"notifications/resources/list_changed"})}async sendToolListChanged(){return this.notification({method:"notifications/tools/list_changed"})}async sendPromptListChanged(){return this.notification({method:"notifications/prompts/list_changed"})}};var As=class{static{o(this,"WebStandardStreamableHTTPServerTransport")}constructor(t={}){this._started=!1,this._hasHandledRequest=!1,this._streamMapping=new Map,this._requestToStreamMapping=new Map,this._requestResponseMap=new Map,this._initialized=!1,this._enableJsonResponse=!1,this._standaloneSseStreamId="_GET_stream",this.sessionIdGenerator=t.sessionIdGenerator,this._enableJsonResponse=t.enableJsonResponse??!1,this._eventStore=t.eventStore,this._onsessioninitialized=t.onsessioninitialized,this._onsessionclosed=t.onsessionclosed,this._allowedHosts=t.allowedHosts,this._allowedOrigins=t.allowedOrigins,this._enableDnsRebindingProtection=t.enableDnsRebindingProtection??!1,this._retryInterval=t.retryInterval}async start(){if(this._started)throw new Error("Transport already started");this._started=!0}createJsonErrorResponse(t,r,n,a){let i={code:r,message:n};return a?.data!==void 0&&(i.data=a.data),new Response(JSON.stringify({jsonrpc:"2.0",error:i,id:null}),{status:t,headers:{"Content-Type":"application/json",...a?.headers}})}validateRequestHeaders(t){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let r=t.headers.get("host");if(!r||!this._allowedHosts.includes(r)){let n=`Invalid Host header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let r=t.headers.get("origin");if(r&&!this._allowedOrigins.includes(r)){let n=`Invalid Origin header: ${r}`;return this.onerror?.(new Error(n)),this.createJsonErrorResponse(403,-32e3,n)}}}}async handleRequest(t,r){if(!this.sessionIdGenerator&&this._hasHandledRequest)throw new Error("Stateless transport cannot be reused across requests. Create a new transport per request.");this._hasHandledRequest=!0;let n=this.validateRequestHeaders(t);if(n)return n;switch(t.method){case"POST":return this.handlePostRequest(t,r);case"GET":return this.handleGetRequest(t);case"DELETE":return this.handleDeleteRequest(t);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(t,r,n,a){if(!this._eventStore||a<"2025-11-25")return;let i=await this._eventStore.storeEvent(n,{}),s=`id: ${i}
|
|
41
39
|
data:
|
|
42
40
|
|
|
43
41
|
`;this._retryInterval!==void 0&&(s=`id: ${i}
|
|
@@ -48,17 +46,17 @@ data:
|
|
|
48
46
|
`;return a&&(i+=`id: ${a}
|
|
49
47
|
`),i+=`data: ${JSON.stringify(n)}
|
|
50
48
|
|
|
51
|
-
`,t.enqueue(r.encode(i)),!0}catch(i){return this.onerror?.(i),!1}}handleUnsupportedRequest(){return this.onerror?.(new Error("Method not allowed.")),new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Method not allowed."},id:null}),{status:405,headers:{Allow:"GET, POST, DELETE","Content-Type":"application/json"}})}async handlePostRequest(t,r){try{let n=t.headers.get("accept");if(!n?.includes("application/json")||!n.includes("text/event-stream"))return this.onerror?.(new Error("Not Acceptable: Client must accept both application/json and text/event-stream")),this.createJsonErrorResponse(406,-32e3,"Not Acceptable: Client must accept both application/json and text/event-stream");let a=t.headers.get("content-type");if(!a||!a.includes("application/json"))return this.onerror?.(new Error("Unsupported Media Type: Content-Type must be application/json")),this.createJsonErrorResponse(415,-32e3,"Unsupported Media Type: Content-Type must be application/json");let i={headers:Object.fromEntries(t.headers.entries()),url:new URL(t.url)},s;if(r?.parsedBody!==void 0)s=r.parsedBody;else try{s=await t.json()}catch{return this.onerror?.(new Error("Parse error: Invalid JSON")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON")}let c;try{Array.isArray(s)?c=s.map(w=>Dr.parse(w)):c=[Dr.parse(s)]}catch{return this.onerror?.(new Error("Parse error: Invalid JSON-RPC message")),this.createJsonErrorResponse(400,-32700,"Parse error: Invalid JSON-RPC message")}let d=c.some(eu);if(d){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(new Error("Invalid Request: Server already initialized")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Server already initialized");if(c.length>1)return this.onerror?.(new Error("Invalid Request: Only one initialization request is allowed")),this.createJsonErrorResponse(400,-32600,"Invalid Request: Only one initialization request is allowed");this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!d){let w=this.validateSession(t);if(w)return w;let b=this.validateProtocolVersion(t);if(b)return b}if(!c.some(It)){for(let w of c)this.onmessage?.(w,{authInfo:r?.authInfo,requestInfo:i});return new Response(null,{status:202})}let l=crypto.randomUUID(),m=c.find(w=>eu(w)),h=m?m.params.protocolVersion:t.headers.get("mcp-protocol-version")??Ef;if(this._enableJsonResponse)return new Promise(w=>{this._streamMapping.set(l,{resolveJson:w,cleanup:o(()=>{this._streamMapping.delete(l)},"cleanup")});for(let b of c)It(b)&&this._requestToStreamMapping.set(b.id,l);for(let b of c)this.onmessage?.(b,{authInfo:r?.authInfo,requestInfo:i})});let y=new TextEncoder,v,S=new ReadableStream({start:o(w=>{v=w},"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 w of c)It(w)&&(this._streamMapping.set(l,{controller:v,encoder:y,cleanup:o(()=>{this._streamMapping.delete(l);try{v.close()}catch{}},"cleanup")}),this._requestToStreamMapping.set(w.id,l));await this.writePrimingEvent(v,y,l,h);for(let w of c){let b,R;It(w)&&this._eventStore&&h>="2025-11-25"&&(b=o(()=>{this.closeSSEStream(w.id)},"closeSSEStream"),R=o(()=>{this.closeStandaloneSSEStream()},"closeStandaloneSSEStream")),this.onmessage?.(w,{authInfo:r?.authInfo,requestInfo:i,closeSSEStream:b,closeStandaloneSSEStream:R})}return new Response(S,{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&&!cr.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${cr.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${cr.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((gt(t)||En(t))&&(n=t.id),n===void 0){if(gt(t)||En(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(gt(t)||En(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 ao(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(!ao(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(!ao(e[s],t[s]))return!1;return!0}return e===t}o(ao,"deepCompareStrict");function ot(e){return encodeURI(IU(e))}o(ot,"encodePointer");function IU(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(IU,"escapePointer");var PU={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},xU={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},kU={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},TU=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Xt(e,t=Object.create(null),r=TU,n=""){if(e&&typeof e=="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let s=new URL(i,r.href);s.hash.length>1?t[s.href]=e:(s.hash="",n===""?r=s:Xt(e,t,r))}}else if(e!==!0&&e!==!1)return t;let a=r.href+(n?"#"+n:"");if(t[a]!==void 0)throw new Error(`Duplicate schema URI "${a}".`);if(t[a]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:a}),e.$ref&&e.__absolute_ref__===void 0){let i=new URL(e.$ref,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=new URL(e.$recursiveRef,r.href);i.hash=i.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=new URL("#"+e.$anchor,r.href);t[i.href]=e}for(let i in e){if(kU[i])continue;let s=`${n}/${ot(i)}`,c=e[i];if(Array.isArray(c)){if(PU[i]){let d=c.length;for(let p=0;p<d;p++)Xt(c[p],t,r,`${s}/${p}`)}}else if(xU[i])for(let d in c)Xt(c[d],t,r,`${s}/${ot(d)}`);else Xt(c,t,r,s)}return t}o(Xt,"dereference");var AU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,EU=[0,31,28,31,30,31,30,31,31,30,31,30,31],UU=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,OU=/^(?=.{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,$U=/^(?:[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,zU=/^(?:(?:[^\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,MU=/^(?:(?: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,qU=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,NU=/^(?:\/(?:[^~/]|~0|~1)*)*$/,DU=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,jU=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,HU=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"),LU=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,BU=/^((([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,GU=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 $t(e){return e.test.bind(e)}o($t,"bind");var np={date:iv,time:sv.bind(void 0,!1),"date-time":ZU,duration:GU,uri:WU,"uri-reference":$t($U),"uri-template":$t(zU),url:$t(MU),email:HU,hostname:$t(OU),ipv4:$t(LU),ipv6:$t(BU),regex:QU,uuid:$t(qU),"json-pointer":$t(NU),"json-pointer-uri-fragment":$t(DU),"relative-json-pointer":$t(jU)};function VU(e){return e%4===0&&(e%100!==0||e%400===0)}o(VU,"isLeapYear");function iv(e){let t=e.match(AU);if(!t)return!1;let r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&VU(r)?29:EU[n])}o(iv,"date");function sv(e,t){let r=t.match(UU);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(sv,"time");var FU=/t|\s/i;function ZU(e){let t=e.split(FU);return t.length==2&&iv(t[0])&&sv(!0,t[1])}o(ZU,"date_time");var KU=/\/|:/,JU=/^(?:[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 WU(e){return KU.test(e)&&JU.test(e)}o(WU,"uri");var YU=/[^\\]\\Z/;function QU(e){if(YU.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}o(QU,"regex");var cv;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(cv||(cv={}));function uv(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(uv,"ucs2length");function he(e,t,r="2019-09",n=Xt(t),a=!0,i=null,s="#",c="#",d=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let p=typeof e,l;switch(p){case"boolean":case"number":case"string":l=p;break;case"object":e===null?l="null":Array.isArray(e)?l="array":l="object";break;default:throw new Error(`Instances of "${p}" type are not supported.`)}let{$ref:m,$recursiveRef:h,$recursiveAnchor:y,type:v,const:S,enum:_,required:w,not:b,anyOf:R,allOf:z,oneOf:M,if:Me,then:at,else:yn,format:or,properties:Mt,patternProperties:Er,additionalProperties:po,unevaluatedProperties:mo,minProperties:fo,maxProperties:Xs,propertyNames:Dp,dependentRequired:ec,dependentSchemas:tc,dependencies:rc,prefixItems:nc,items:ho,additionalItems:jp,unevaluatedItems:Hp,contains:Lp,minContains:qt,maxContains:Da,minItems:oc,maxItems:ac,uniqueItems:Rw,minimum:Ur,maximum:Or,exclusiveMinimum:go,exclusiveMaximum:yo,multipleOf:ja,minLength:Ha,maxLength:La,pattern:Bp,__absolute_ref__:Ba,__absolute_recursive_ref__:Cw}=t,T=[];if(y===!0&&i===null&&(i=t),h==="#"){let q=i===null?n[Cw]:i,$=`${c}/$recursiveRef`,H=he(e,i===null?t:i,r,n,a,q,s,$,d);H.valid||T.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:$,error:"A subschema had errors."},...H.errors)}if(m!==void 0){let $=n[Ba||m];if($===void 0){let P=`Unresolved $ref "${m}".`;throw Ba&&Ba!==m&&(P+=` Absolute URI "${Ba}".`),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(w=>Br.parse(w)):c=[Br.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(tu);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 w=this.validateSession(t);if(w)return w;let b=this.validateProtocolVersion(t);if(b)return b}if(!c.some(Tt)){for(let w of c)this.onmessage?.(w,{authInfo:r?.authInfo,requestInfo:i});return new Response(null,{status:202})}let l=crypto.randomUUID(),m=c.find(w=>tu(w)),h=m?m.params.protocolVersion:t.headers.get("mcp-protocol-version")??jf;if(this._enableJsonResponse)return new Promise(w=>{this._streamMapping.set(l,{resolveJson:w,cleanup:o(()=>{this._streamMapping.delete(l)},"cleanup")});for(let b of c)Tt(b)&&this._requestToStreamMapping.set(b.id,l);for(let b of c)this.onmessage?.(b,{authInfo:r?.authInfo,requestInfo:i})});let y=new TextEncoder,v,S=new ReadableStream({start:o(w=>{v=w},"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 w of c)Tt(w)&&(this._streamMapping.set(l,{controller:v,encoder:y,cleanup:o(()=>{this._streamMapping.delete(l);try{v.close()}catch{}},"cleanup")}),this._requestToStreamMapping.set(w.id,l));await this.writePrimingEvent(v,y,l,h);for(let w of c){let b,R;Tt(w)&&this._eventStore&&h>="2025-11-25"&&(b=o(()=>{this.closeSSEStream(w.id)},"closeSSEStream"),R=o(()=>{this.closeStandaloneSSEStream()},"closeStandaloneSSEStream")),this.onmessage?.(w,{authInfo:r?.authInfo,requestInfo:i,closeSSEStream:b,closeStandaloneSSEStream:R})}return new Response(S,{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&&!mr.includes(r))return this.onerror?.(new Error(`Bad Request: Unsupported protocol version: ${r} (supported versions: ${mr.join(", ")})`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Unsupported protocol version: ${r} (supported versions: ${mr.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((_t(t)||Mn(t))&&(n=t.id),n===void 0){if(_t(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(_t(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 co(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(!co(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(!co(e[s],t[s]))return!1;return!0}return e===t}o(co,"deepCompareStrict");function ct(e){return encodeURI(UU(e))}o(ct,"encodePointer");function UU(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}o(UU,"escapePointer");var OU={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},$U={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},MU={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},zU=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 rr(e,t=Object.create(null),r=zU,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:rr(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(MU[i])continue;let s=`${n}/${ct(i)}`,c=e[i];if(Array.isArray(c)){if(OU[i]){let d=c.length;for(let p=0;p<d;p++)rr(c[p],t,r,`${s}/${p}`)}}else if($U[i])for(let d in c)rr(c[d],t,r,`${s}/${ct(d)}`);else rr(c,t,r,s)}return t}o(rr,"dereference");var qU=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,NU=[0,31,28,31,30,31,30,31,31,30,31,30,31],jU=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,DU=/^(?=.{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,HU=/^(?:[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,LU=/^(?:(?:[^\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,BU=/^(?:(?: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,GU=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,VU=/^(?:\/(?:[^~/]|~0|~1)*)*$/,FU=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,ZU=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,KU=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"),JU=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,WU=/^((([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,YU=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 Nt(e){return e.test.bind(e)}o(Nt,"bind");var np={date:gv,time:yv.bind(void 0,!1),"date-time":eO,duration:YU,uri:nO,"uri-reference":Nt(HU),"uri-template":Nt(LU),url:Nt(BU),email:KU,hostname:Nt(DU),ipv4:Nt(JU),ipv6:Nt(WU),regex:aO,uuid:Nt(GU),"json-pointer":Nt(VU),"json-pointer-uri-fragment":Nt(FU),"relative-json-pointer":Nt(ZU)};function QU(e){return e%4===0&&(e%100!==0||e%400===0)}o(QU,"isLeapYear");function gv(e){let t=e.match(qU);if(!t)return!1;let r=+t[1],n=+t[2],a=+t[3];return n>=1&&n<=12&&a>=1&&a<=(n==2&&QU(r)?29:NU[n])}o(gv,"date");function yv(e,t){let r=t.match(jU);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(yv,"time");var XU=/t|\s/i;function eO(e){let t=e.split(XU);return t.length==2&&gv(t[0])&&yv(!0,t[1])}o(eO,"date_time");var tO=/\/|:/,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 nO(e){return tO.test(e)&&rO.test(e)}o(nO,"uri");var oO=/[^\\]\\Z/;function aO(e){if(oO.test(e))return!1;try{return new RegExp(e,"u"),!0}catch{return!1}}o(aO,"regex");var Sv;(function(e){e[e.Flag=1]="Flag",e[e.Basic=2]="Basic",e[e.Detailed=4]="Detailed"})(Sv||(Sv={}));function vv(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(vv,"ucs2length");function he(e,t,r="2019-09",n=rr(t),a=!0,i=null,s="#",c="#",d=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:s,keyword:"false",keywordLocation:s,error:"False boolean schema."}]};let p=typeof e,l;switch(p){case"boolean":case"number":case"string":l=p;break;case"object":e===null?l="null":Array.isArray(e)?l="array":l="object";break;default:throw new Error(`Instances of "${p}" type are not supported.`)}let{$ref:m,$recursiveRef:h,$recursiveAnchor:y,type:v,const:S,enum:_,required:w,not:b,anyOf:R,allOf:z,oneOf:q,if:je,then:ut,else:wn,format:sr,properties:Dt,patternProperties:qr,additionalProperties:ho,unevaluatedProperties:go,minProperties:yo,maxProperties:ec,propertyNames:Dp,dependentRequired:tc,dependentSchemas:rc,dependencies:nc,prefixItems:oc,items:So,additionalItems:Hp,unevaluatedItems:Lp,contains:Bp,minContains:Ht,maxContains:Ba,minItems:ac,maxItems:ic,uniqueItems:Aw,minimum:Nr,maximum:jr,exclusiveMinimum:vo,exclusiveMaximum:_o,multipleOf:Ga,minLength:Va,maxLength:Fa,pattern:Gp,__absolute_ref__:Za,__absolute_recursive_ref__:Ew}=t,T=[];if(y===!0&&i===null&&(i=t),h==="#"){let N=i===null?n[Ew]:i,$=`${c}/$recursiveRef`,L=he(e,i===null?t:i,r,n,a,N,s,$,d);L.valid||T.push({instanceLocation:s,keyword:"$recursiveRef",keywordLocation:$,error:"A subschema had errors."},...L.errors)}if(m!==void 0){let $=n[Za||m];if($===void 0){let P=`Unresolved $ref "${m}".`;throw Za&&Za!==m&&(P+=` Absolute URI "${Za}".`),P+=`
|
|
52
50
|
Known schemas:
|
|
53
51
|
- ${Object.keys(n).join(`
|
|
54
|
-
- `)}`,new Error(P)}let H=`${c}/$ref`,A=he(e,$,r,n,a,i,s,H,d);if(A.valid||T.push({instanceLocation:s,keyword:"$ref",keywordLocation:H,error:"A subschema had errors."},...A.errors),r==="4"||r==="7")return{valid:T.length===0,errors:T}}if(Array.isArray(v)){let q=v.length,$=!1;for(let H=0;H<q;H++)if(l===v[H]||v[H]==="integer"&&l==="number"&&e%1===0&&e===e){$=!0;break}$||T.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${v.join('", "')}".`})}else v==="integer"?(l!=="number"||e%1||e!==e)&&T.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${v}".`}):v!==void 0&&l!==v&&T.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${v}".`});if(S!==void 0&&(l==="object"||l==="array"?ao(e,S)||T.push({instanceLocation:s,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(S)}.`}):e!==S&&T.push({instanceLocation:s,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(S)}.`})),_!==void 0&&(l==="object"||l==="array"?_.some(q=>ao(e,q))||T.push({instanceLocation:s,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(_)}.`}):_.some(q=>e===q)||T.push({instanceLocation:s,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(_)}.`})),b!==void 0){let q=`${c}/not`;he(e,b,r,n,a,i,s,q).valid&&T.push({instanceLocation:s,keyword:"not",keywordLocation:q,error:'Instance matched "not" schema.'})}let Ga=[];if(R!==void 0){let q=`${c}/anyOf`,$=T.length,H=!1;for(let A=0;A<R.length;A++){let P=R[A],D=Object.create(d),N=he(e,P,r,n,a,y===!0?i:null,s,`${q}/${A}`,D);T.push(...N.errors),H=H||N.valid,N.valid&&Ga.push(D)}H?T.length=$:T.splice($,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:q,error:"Instance does not match any subschemas."})}if(z!==void 0){let q=`${c}/allOf`,$=T.length,H=!0;for(let A=0;A<z.length;A++){let P=z[A],D=Object.create(d),N=he(e,P,r,n,a,y===!0?i:null,s,`${q}/${A}`,D);T.push(...N.errors),H=H&&N.valid,N.valid&&Ga.push(D)}H?T.length=$:T.splice($,0,{instanceLocation:s,keyword:"allOf",keywordLocation:q,error:"Instance does not match every subschema."})}if(M!==void 0){let q=`${c}/oneOf`,$=T.length,H=M.filter((A,P)=>{let D=Object.create(d),N=he(e,A,r,n,a,y===!0?i:null,s,`${q}/${P}`,D);return T.push(...N.errors),N.valid&&Ga.push(D),N.valid}).length;H===1?T.length=$:T.splice($,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:q,error:`Instance does not match exactly one subschema (${H} matches).`})}if((l==="object"||l==="array")&&Object.assign(d,...Ga),Me!==void 0){let q=`${c}/if`;if(he(e,Me,r,n,a,i,s,q,d).valid){if(at!==void 0){let H=he(e,at,r,n,a,i,s,`${c}/then`,d);H.valid||T.push({instanceLocation:s,keyword:"if",keywordLocation:q,error:'Instance does not match "then" schema.'},...H.errors)}}else if(yn!==void 0){let H=he(e,yn,r,n,a,i,s,`${c}/else`,d);H.valid||T.push({instanceLocation:s,keyword:"if",keywordLocation:q,error:'Instance does not match "else" schema.'},...H.errors)}}if(l==="object"){if(w!==void 0)for(let A of w)A in e||T.push({instanceLocation:s,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${A}".`});let q=Object.keys(e);if(fo!==void 0&&q.length<fo&&T.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${fo} properties.`}),Xs!==void 0&&q.length>Xs&&T.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${Xs} properties.`}),Dp!==void 0){let A=`${c}/propertyNames`;for(let P in e){let D=`${s}/${ot(P)}`,N=he(P,Dp,r,n,a,i,D,A);N.valid||T.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:A,error:`Property name "${P}" does not match schema.`},...N.errors)}}if(ec!==void 0){let A=`${c}/dependantRequired`;for(let P in ec)if(P in e){let D=ec[P];for(let N of D)N in e||T.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:A,error:`Instance has "${P}" but does not have "${N}".`})}}if(tc!==void 0)for(let A in tc){let P=`${c}/dependentSchemas`;if(A in e){let D=he(e,tc[A],r,n,a,i,s,`${P}/${ot(A)}`,d);D.valid||T.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:P,error:`Instance has "${A}" but does not match dependant schema.`},...D.errors)}}if(rc!==void 0){let A=`${c}/dependencies`;for(let P in rc)if(P in e){let D=rc[P];if(Array.isArray(D))for(let N of D)N in e||T.push({instanceLocation:s,keyword:"dependencies",keywordLocation:A,error:`Instance has "${P}" but does not have "${N}".`});else{let N=he(e,D,r,n,a,i,s,`${A}/${ot(P)}`);N.valid||T.push({instanceLocation:s,keyword:"dependencies",keywordLocation:A,error:`Instance has "${P}" but does not match dependant schema.`},...N.errors)}}}let $=Object.create(null),H=!1;if(Mt!==void 0){let A=`${c}/properties`;for(let P in Mt){if(!(P in e))continue;let D=`${s}/${ot(P)}`,N=he(e[P],Mt[P],r,n,a,i,D,`${A}/${ot(P)}`);if(N.valid)d[P]=$[P]=!0;else if(H=a,T.push({instanceLocation:s,keyword:"properties",keywordLocation:A,error:`Property "${P}" does not match schema.`},...N.errors),H)break}}if(!H&&Er!==void 0){let A=`${c}/patternProperties`;for(let P in Er){let D=new RegExp(P,"u"),N=Er[P];for(let Ze in e){if(!D.test(Ze))continue;let Gp=`${s}/${ot(Ze)}`,Vp=he(e[Ze],N,r,n,a,i,Gp,`${A}/${ot(P)}`);Vp.valid?d[Ze]=$[Ze]=!0:(H=a,T.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:A,error:`Property "${Ze}" matches pattern "${P}" but does not match associated schema.`},...Vp.errors))}}}if(!H&&po!==void 0){let A=`${c}/additionalProperties`;for(let P in e){if($[P])continue;let D=`${s}/${ot(P)}`,N=he(e[P],po,r,n,a,i,D,A);N.valid?d[P]=!0:(H=a,T.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:A,error:`Property "${P}" does not match additional properties schema.`},...N.errors))}}else if(!H&&mo!==void 0){let A=`${c}/unevaluatedProperties`;for(let P in e)if(!d[P]){let D=`${s}/${ot(P)}`,N=he(e[P],mo,r,n,a,i,D,A);N.valid?d[P]=!0:T.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:A,error:`Property "${P}" does not match unevaluated properties schema.`},...N.errors)}}}else if(l==="array"){ac!==void 0&&e.length>ac&&T.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${c}/maxItems`,error:`Array has too many items (${e.length} > ${ac}).`}),oc!==void 0&&e.length<oc&&T.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${c}/minItems`,error:`Array has too few items (${e.length} < ${oc}).`});let q=e.length,$=0,H=!1;if(nc!==void 0){let A=`${c}/prefixItems`,P=Math.min(nc.length,q);for(;$<P;$++){let D=he(e[$],nc[$],r,n,a,i,`${s}/${$}`,`${A}/${$}`);if(d[$]=!0,!D.valid&&(H=a,T.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:A,error:"Items did not match schema."},...D.errors),H))break}}if(ho!==void 0){let A=`${c}/items`;if(Array.isArray(ho)){let P=Math.min(ho.length,q);for(;$<P;$++){let D=he(e[$],ho[$],r,n,a,i,`${s}/${$}`,`${A}/${$}`);if(d[$]=!0,!D.valid&&(H=a,T.push({instanceLocation:s,keyword:"items",keywordLocation:A,error:"Items did not match schema."},...D.errors),H))break}}else for(;$<q;$++){let P=he(e[$],ho,r,n,a,i,`${s}/${$}`,A);if(d[$]=!0,!P.valid&&(H=a,T.push({instanceLocation:s,keyword:"items",keywordLocation:A,error:"Items did not match schema."},...P.errors),H))break}if(!H&&jp!==void 0){let P=`${c}/additionalItems`;for(;$<q;$++){let D=he(e[$],jp,r,n,a,i,`${s}/${$}`,P);d[$]=!0,D.valid||(H=a,T.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:P,error:"Items did not match additional items schema."},...D.errors))}}}if(Lp!==void 0)if(q===0&&qt===void 0)T.push({instanceLocation:s,keyword:"contains",keywordLocation:`${c}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(qt!==void 0&&q<qt)T.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array has less items (${q}) than minContains (${qt}).`});else{let A=`${c}/contains`,P=T.length,D=0;for(let N=0;N<q;N++){let Ze=he(e[N],Lp,r,n,a,i,`${s}/${N}`,A);Ze.valid?(d[N]=!0,D++):T.push(...Ze.errors)}D>=(qt||0)&&(T.length=P),qt===void 0&&Da===void 0&&D===0?T.splice(P,0,{instanceLocation:s,keyword:"contains",keywordLocation:A,error:"Array does not contain item matching schema."}):qt!==void 0&&D<qt?T.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array must contain at least ${qt} items matching schema. Only ${D} items were found.`}):Da!==void 0&&D>Da&&T.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${c}/maxContains`,error:`Array may contain at most ${Da} items matching schema. ${D} items were found.`})}if(!H&&Hp!==void 0){let A=`${c}/unevaluatedItems`;for($;$<q;$++){if(d[$])continue;let P=he(e[$],Hp,r,n,a,i,`${s}/${$}`,A);d[$]=!0,P.valid||T.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:A,error:"Items did not match unevaluated items schema."},...P.errors)}}if(Rw)for(let A=0;A<q;A++){let P=e[A],D=typeof P=="object"&&P!==null;for(let N=0;N<q;N++){if(A===N)continue;let Ze=e[N];(P===Ze||D&&(typeof Ze=="object"&&Ze!==null)&&ao(P,Ze))&&(T.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${A} and ${N}.`}),A=Number.MAX_SAFE_INTEGER,N=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(Ur!==void 0&&(go===!0&&e<=Ur||e<Ur)&&T.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${go?"or equal to ":""} ${Ur}.`}),Or!==void 0&&(yo===!0&&e>=Or||e>Or)&&T.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${yo?"or equal to ":""} ${Or}.`})):(Ur!==void 0&&e<Ur&&T.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${Ur}.`}),Or!==void 0&&e>Or&&T.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${Or}.`}),go!==void 0&&e<=go&&T.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${c}/exclusiveMinimum`,error:`${e} is less than ${go}.`}),yo!==void 0&&e>=yo&&T.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${c}/exclusiveMaximum`,error:`${e} is greater than or equal to ${yo}.`})),ja!==void 0){let q=e%ja;Math.abs(0-q)>=11920929e-14&&Math.abs(ja-q)>=11920929e-14&&T.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${c}/multipleOf`,error:`${e} is not a multiple of ${ja}.`})}}else if(l==="string"){let q=Ha===void 0&&La===void 0?0:uv(e);Ha!==void 0&&q<Ha&&T.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${c}/minLength`,error:`String is too short (${q} < ${Ha}).`}),La!==void 0&&q>La&&T.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${c}/maxLength`,error:`String is too long (${q} > ${La}).`}),Bp!==void 0&&!new RegExp(Bp,"u").test(e)&&T.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${c}/pattern`,error:"String does not match pattern."}),or!==void 0&&np[or]&&!np[or](e)&&T.push({instanceLocation:s,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${or}".`})}return{valid:T.length===0,errors:T}}o(he,"validate");var ks=class{static{o(this,"Validator")}schema;draft;shortCircuit;lookup;constructor(t,r="2019-09",n=!0){this.schema=t,this.draft=r,this.shortCircuit=n,this.lookup=Xt(t)}validate(t){return he(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),Xt(t,this.lookup)}};var io=class{static{o(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let r=new ks(t,this.draft,this.shortcircuit);return n=>{let a=r.validate(n);return a.valid?{valid:!0,data:n,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:a.errors.map(i=>`${i.instanceLocation}: ${i.error}`).join("; ")}}}};import{metrics as XU,context as Ts,propagation as lv,SpanKind as pv,SpanStatusCode as op,trace as Ea}from"@opentelemetry/api";var eO="mcp-gateway",tO="mcp-gateway",rO=$r,nO="2.0",mv=Ea.getTracer(eO),ap=XU.getMeter(tO),oO=ap.createHistogram("mcp.client.operation.duration",{description:"The duration of the MCP request or notification as observed on the sender.",unit:"s"}),aO=ap.createHistogram("mcp.server.operation.duration",{description:"MCP request or notification duration as observed on the receiver.",unit:"s"}),iO=ap.createHistogram("mcp.client.session.duration",{description:"The duration of the MCP session as observed on the MCP client.",unit:"s"}),sO=["traceparent","tracestate","baggage"];function ip(){return performance.now()/1e3}o(ip,"nowSeconds");function fv(e,t){t(Math.max(ip()-e,0))}o(fv,"recordDurationSeconds");function dv(e){return e===void 0?void 0:String(e)}o(dv,"stringifyAttribute");function ze(e,t,r){r!==void 0&&(e[t]=r)}o(ze,"assignAttribute");function cO(e){if(e.capabilityType==="tool"||e.capabilityType==="prompt")return e.capabilityName}o(cO,"readTargetName");function hv(e){let t=cO({kind:"client",...e});return t?`${e.methodName} ${t}`:e.methodName}o(hv,"buildMcpOperationSpanName");function sp(e){let t={"mcp.method.name":e.methodName};return ze(t,"jsonrpc.protocol.version",e.jsonRpcProtocolVersion??nO),ze(t,"jsonrpc.request.id",dv(e.jsonRpcRequestId)),ze(t,"mcp.protocol.version",e.mcpProtocolVersion??rO),ze(t,"mcp.session.id",e.mcpSessionId),ze(t,"mcp.resource.uri",e.resourceUri),ze(t,"rpc.response.status_code",dv(e.rpcResponseStatusCode)),ze(t,"error.type",e.errorType),e.capabilityType==="tool"&&(ze(t,"gen_ai.operation.name","execute_tool"),ze(t,"gen_ai.tool.name",e.capabilityName)),e.capabilityType==="prompt"&&ze(t,"gen_ai.prompt.name",e.capabilityName),ze(t,"network.protocol.name",e.networkProtocolName?.toLowerCase()),ze(t,"network.protocol.version",e.networkProtocolVersion),ze(t,"network.transport",e.networkTransport),ze(t,"server.address",e.serverAddress),ze(t,"server.port",e.serverPort),ze(t,"client.address",e.clientAddress),ze(t,"client.port",e.clientPort),t}o(sp,"buildMcpOperationAttributes");function uO(e){let t=sp({methodName:"initialize",...e});return delete t["mcp.method.name"],t}o(uO,"buildMcpSessionAttributes");function gv(e,t,r){e.setAttribute("error.type",r),e.setStatus({code:op.ERROR}),t instanceof Error&&e.recordException(t)}o(gv,"setSpanError");function yv(e){let t=e?.code;return typeof t=="string"||typeof t=="number"?String(t):e instanceof Error?e.name:"_OTHER"}o(yv,"readErrorType");function dO(e){let t=e&&typeof e=="object"?e._meta:void 0;return!t||typeof t!="object"?Ts.active():lv.extract(Ts.active(),t,{get(r,n){let a=r[n];return typeof a=="string"?a:void 0},keys(r){return Object.keys(r)}})}o(dO,"readServerParentContext");function lO(e){let t=Ea.getSpanContext(Ts.active()),r=Ea.getSpanContext(e);if(!(!t||!Ea.isSpanContextValid(t))&&!(r&&Ea.isSpanContextValid(r)&&t.traceId===r.traceId&&t.spanId===r.spanId))return[{context:t}]}o(lO,"readAmbientSpanLink");function Sv(e){return e&&typeof e=="object"&&e.isError===!0?"tool_error":void 0}o(Sv,"readResultErrorType");async function Pr(e,t){let r=ip(),n=sp({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});return mv.startActiveSpan(hv(e),{kind:pv.CLIENT,attributes:n},async a=>{try{let i=await t(),s=Sv(i);return s&&(a.setAttribute("error.type",s),a.setStatus({code:op.ERROR}),n["error.type"]=s),i}catch(i){let s=e.errorType??yv(i);throw n["error.type"]=s,gv(a,i,s),i}finally{fv(r,i=>{oO.record(i,n)}),a.end()}})}o(Pr,"runMcpClientOperation");async function xr(e,t){let r=ip(),n=dO(e.params),a=sp({kind:"server",networkProtocolName:"http",networkTransport:"tcp",...e}),i=lO(n);return mv.startActiveSpan(hv(e),{kind:pv.SERVER,attributes:a,...i?{links:i}:{}},n,async s=>{try{let c=await t(),d=Sv(c);return d&&(s.setAttribute("error.type",d),s.setStatus({code:op.ERROR}),a["error.type"]=d),c}catch(c){let d=e.errorType??yv(c);throw a["error.type"]=d,gv(s,c,d),c}finally{fv(r,c=>{aO.record(c,a)}),s.end()}})}o(xr,"runMcpServerOperation");function vv(e){let t={...e??{},_meta:{...e?._meta&&typeof e._meta=="object"?e._meta:{}}};return lv.inject(Ts.active(),t._meta,{set(r,n,a){sO.includes(n)&&(r[n]=a)}}),t}o(vv,"injectMcpTraceContextIntoParams");function _v(e,t){let r=uO({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});iO.record(Math.max(t,0),r)}o(_v,"recordMcpClientSessionDuration");var As=class{static{o(this,"ExperimentalClientTasks")}constructor(t){this._client=t}async*callToolStream(t,r=dr,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 x(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 x(E.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof x){yield{type:"error",error:l};return}yield{type:"error",error:new x(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 Es(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&&Es(i,r[a])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&Es(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&Es(r,t)}}o(Es,"applyElicitationDefaults");function pO(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(pO,"getSupportedElicitationModes");var Us=class extends Hn{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 oo,r?.listChanged&&(this._pendingListChangedConfig=r.listChanged)}_setupListChangedHandlers(t){t.tools&&this._serverCapabilities?.tools?.listChanged&&this._setupListChangedHandler("tools",bu,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",vu,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",du,t.resources,async()=>(await this.listResources()).resources)}get experimental(){return this._experimental||(this._experimental={tasks:new As(this)}),this._experimental}registerCapabilities(t){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=ji(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(gr(a)){let c=a;i=c._zod?.def?.value??c.value}else{let c=a;i=c._def?.value??c.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let c=o(async(d,p)=>{let l=Ge(Iu,d);if(!l.success){let b=l.error instanceof Error?l.error.message:String(l.error);throw new x(E.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:m}=l.data;m.mode=m.mode??"form";let{supportsFormMode:h,supportsUrlMode:y}=pO(this._capabilities.elicitation);if(m.mode==="form"&&!h)throw new x(E.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!y)throw new x(E.InvalidParams,"Client does not support URL-mode elicitation requests");let v=await Promise.resolve(r(d,p));if(m.task){let b=Ge(Bt,v);if(!b.success){let R=b.error instanceof Error?b.error.message:String(b.error);throw new x(E.InvalidParams,`Invalid task creation result: ${R}`)}return b.data}let S=Ge(lr,v);if(!S.success){let b=S.error instanceof Error?S.error.message:String(S.error);throw new x(E.InvalidParams,`Invalid elicitation result: ${b}`)}let _=S.data,w=m.mode==="form"?m.requestedSchema:void 0;if(m.mode==="form"&&_.action==="accept"&&_.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{Es(w,_.content)}catch{}return _},"wrappedHandler");return super.setRequestHandler(t,c)}if(s==="sampling/createMessage"){let c=o(async(d,p)=>{let l=Ge(Cu,d);if(!l.success){let _=l.error instanceof Error?l.error.message:String(l.error);throw new x(E.InvalidParams,`Invalid sampling request: ${_}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let _=Ge(Bt,h);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new x(E.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let v=m.tools||m.toolChoice?No:jr,S=Ge(v,h);if(!S.success){let _=S.error instanceof Error?S.error.message:String(S.error);throw new x(E.InvalidParams,`Invalid sampling result: ${_}`)}return S.data},"wrappedHandler");return super.setRequestHandler(t,c)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:sr,capabilities:this._capabilities,clientInfo:this._clientInfo}},tu,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!cr.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){Cs(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&Is(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Lt,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},Pu,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Lt,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},Su,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},pu,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},ou,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},iu,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},uu,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Lt,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Lt,r)}async callTool(t,r=dr,n){if(this.isToolTaskRequired(t.name))throw new x(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 x(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 x(E.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof x?s:new x(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},wu,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,a){let i=Vf.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 Os(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}o(Os,"normalizeHeaders");function wv(e=fetch,t){return t?async(r,n)=>{let a={...t,...n,headers:n?.headers?{...Os(t.headers),...Os(n.headers)}:t.headers};return e(r,a)}:e}o(wv,"createFetchWithInit");var $s=class extends Error{static{o(this,"ParseError")}constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function cp(e){}o(cp,"noop");function bv(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=cp,onError:r=cp,onRetry:n=cp,onComment:a}=e,i="",s=!0,c,d="",p="";function l(S){let _=s?S.replace(/^\xEF\xBB\xBF/,""):S,[w,b]=mO(`${i}${_}`);for(let R of w)m(R);i=b,s=!1}o(l,"feed");function m(S){if(S===""){y();return}if(S.startsWith(":")){a&&a(S.slice(S.startsWith(": ")?2:1));return}let _=S.indexOf(":");if(_!==-1){let w=S.slice(0,_),b=S[_+1]===" "?2:1,R=S.slice(_+b);h(w,R,S);return}h(S,"",S)}o(m,"parseLine");function h(S,_,w){switch(S){case"event":p=_;break;case"data":d=`${d}${_}
|
|
55
|
-
`;break;case"id":c=_.includes("\0")?void 0:_;break;case"retry":/^\d+$/.test(_)?n(parseInt(_,10)):r(new
|
|
56
|
-
`)?d.slice(0,-1):d}),c=void 0,d="",p=""}o(y,"dispatchEvent");function v(S={}){i&&S.consume&&m(i),s=!0,c=void 0,d="",p="",i=""}return o(v,"reset"),{feed:l,reset:v}}o(
|
|
52
|
+
- `)}`,new Error(P)}let L=`${c}/$ref`,E=he(e,$,r,n,a,i,s,L,d);if(E.valid||T.push({instanceLocation:s,keyword:"$ref",keywordLocation:L,error:"A subschema had errors."},...E.errors),r==="4"||r==="7")return{valid:T.length===0,errors:T}}if(Array.isArray(v)){let N=v.length,$=!1;for(let L=0;L<N;L++)if(l===v[L]||v[L]==="integer"&&l==="number"&&e%1===0&&e===e){$=!0;break}$||T.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${v.join('", "')}".`})}else v==="integer"?(l!=="number"||e%1||e!==e)&&T.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${v}".`}):v!==void 0&&l!==v&&T.push({instanceLocation:s,keyword:"type",keywordLocation:`${c}/type`,error:`Instance type "${l}" is invalid. Expected "${v}".`});if(S!==void 0&&(l==="object"||l==="array"?co(e,S)||T.push({instanceLocation:s,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(S)}.`}):e!==S&&T.push({instanceLocation:s,keyword:"const",keywordLocation:`${c}/const`,error:`Instance does not match ${JSON.stringify(S)}.`})),_!==void 0&&(l==="object"||l==="array"?_.some(N=>co(e,N))||T.push({instanceLocation:s,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(_)}.`}):_.some(N=>e===N)||T.push({instanceLocation:s,keyword:"enum",keywordLocation:`${c}/enum`,error:`Instance does not match any of ${JSON.stringify(_)}.`})),b!==void 0){let N=`${c}/not`;he(e,b,r,n,a,i,s,N).valid&&T.push({instanceLocation:s,keyword:"not",keywordLocation:N,error:'Instance matched "not" schema.'})}let Ka=[];if(R!==void 0){let N=`${c}/anyOf`,$=T.length,L=!1;for(let E=0;E<R.length;E++){let P=R[E],D=Object.create(d),j=he(e,P,r,n,a,y===!0?i:null,s,`${N}/${E}`,D);T.push(...j.errors),L=L||j.valid,j.valid&&Ka.push(D)}L?T.length=$:T.splice($,0,{instanceLocation:s,keyword:"anyOf",keywordLocation:N,error:"Instance does not match any subschemas."})}if(z!==void 0){let N=`${c}/allOf`,$=T.length,L=!0;for(let E=0;E<z.length;E++){let P=z[E],D=Object.create(d),j=he(e,P,r,n,a,y===!0?i:null,s,`${N}/${E}`,D);T.push(...j.errors),L=L&&j.valid,j.valid&&Ka.push(D)}L?T.length=$:T.splice($,0,{instanceLocation:s,keyword:"allOf",keywordLocation:N,error:"Instance does not match every subschema."})}if(q!==void 0){let N=`${c}/oneOf`,$=T.length,L=q.filter((E,P)=>{let D=Object.create(d),j=he(e,E,r,n,a,y===!0?i:null,s,`${N}/${P}`,D);return T.push(...j.errors),j.valid&&Ka.push(D),j.valid}).length;L===1?T.length=$:T.splice($,0,{instanceLocation:s,keyword:"oneOf",keywordLocation:N,error:`Instance does not match exactly one subschema (${L} matches).`})}if((l==="object"||l==="array")&&Object.assign(d,...Ka),je!==void 0){let N=`${c}/if`;if(he(e,je,r,n,a,i,s,N,d).valid){if(ut!==void 0){let L=he(e,ut,r,n,a,i,s,`${c}/then`,d);L.valid||T.push({instanceLocation:s,keyword:"if",keywordLocation:N,error:'Instance does not match "then" schema.'},...L.errors)}}else if(wn!==void 0){let L=he(e,wn,r,n,a,i,s,`${c}/else`,d);L.valid||T.push({instanceLocation:s,keyword:"if",keywordLocation:N,error:'Instance does not match "else" schema.'},...L.errors)}}if(l==="object"){if(w!==void 0)for(let E of w)E in e||T.push({instanceLocation:s,keyword:"required",keywordLocation:`${c}/required`,error:`Instance does not have required property "${E}".`});let N=Object.keys(e);if(yo!==void 0&&N.length<yo&&T.push({instanceLocation:s,keyword:"minProperties",keywordLocation:`${c}/minProperties`,error:`Instance does not have at least ${yo} properties.`}),ec!==void 0&&N.length>ec&&T.push({instanceLocation:s,keyword:"maxProperties",keywordLocation:`${c}/maxProperties`,error:`Instance does not have at least ${ec} properties.`}),Dp!==void 0){let E=`${c}/propertyNames`;for(let P in e){let D=`${s}/${ct(P)}`,j=he(P,Dp,r,n,a,i,D,E);j.valid||T.push({instanceLocation:s,keyword:"propertyNames",keywordLocation:E,error:`Property name "${P}" does not match schema.`},...j.errors)}}if(tc!==void 0){let E=`${c}/dependantRequired`;for(let P in tc)if(P in e){let D=tc[P];for(let j of D)j in e||T.push({instanceLocation:s,keyword:"dependentRequired",keywordLocation:E,error:`Instance has "${P}" but does not have "${j}".`})}}if(rc!==void 0)for(let E in rc){let P=`${c}/dependentSchemas`;if(E in e){let D=he(e,rc[E],r,n,a,i,s,`${P}/${ct(E)}`,d);D.valid||T.push({instanceLocation:s,keyword:"dependentSchemas",keywordLocation:P,error:`Instance has "${E}" but does not match dependant schema.`},...D.errors)}}if(nc!==void 0){let E=`${c}/dependencies`;for(let P in nc)if(P in e){let D=nc[P];if(Array.isArray(D))for(let j of D)j in e||T.push({instanceLocation:s,keyword:"dependencies",keywordLocation:E,error:`Instance has "${P}" but does not have "${j}".`});else{let j=he(e,D,r,n,a,i,s,`${E}/${ct(P)}`);j.valid||T.push({instanceLocation:s,keyword:"dependencies",keywordLocation:E,error:`Instance has "${P}" but does not match dependant schema.`},...j.errors)}}}let $=Object.create(null),L=!1;if(Dt!==void 0){let E=`${c}/properties`;for(let P in Dt){if(!(P in e))continue;let D=`${s}/${ct(P)}`,j=he(e[P],Dt[P],r,n,a,i,D,`${E}/${ct(P)}`);if(j.valid)d[P]=$[P]=!0;else if(L=a,T.push({instanceLocation:s,keyword:"properties",keywordLocation:E,error:`Property "${P}" does not match schema.`},...j.errors),L)break}}if(!L&&qr!==void 0){let E=`${c}/patternProperties`;for(let P in qr){let D=new RegExp(P,"u"),j=qr[P];for(let Ze in e){if(!D.test(Ze))continue;let Vp=`${s}/${ct(Ze)}`,Fp=he(e[Ze],j,r,n,a,i,Vp,`${E}/${ct(P)}`);Fp.valid?d[Ze]=$[Ze]=!0:(L=a,T.push({instanceLocation:s,keyword:"patternProperties",keywordLocation:E,error:`Property "${Ze}" matches pattern "${P}" but does not match associated schema.`},...Fp.errors))}}}if(!L&&ho!==void 0){let E=`${c}/additionalProperties`;for(let P in e){if($[P])continue;let D=`${s}/${ct(P)}`,j=he(e[P],ho,r,n,a,i,D,E);j.valid?d[P]=!0:(L=a,T.push({instanceLocation:s,keyword:"additionalProperties",keywordLocation:E,error:`Property "${P}" does not match additional properties schema.`},...j.errors))}}else if(!L&&go!==void 0){let E=`${c}/unevaluatedProperties`;for(let P in e)if(!d[P]){let D=`${s}/${ct(P)}`,j=he(e[P],go,r,n,a,i,D,E);j.valid?d[P]=!0:T.push({instanceLocation:s,keyword:"unevaluatedProperties",keywordLocation:E,error:`Property "${P}" does not match unevaluated properties schema.`},...j.errors)}}}else if(l==="array"){ic!==void 0&&e.length>ic&&T.push({instanceLocation:s,keyword:"maxItems",keywordLocation:`${c}/maxItems`,error:`Array has too many items (${e.length} > ${ic}).`}),ac!==void 0&&e.length<ac&&T.push({instanceLocation:s,keyword:"minItems",keywordLocation:`${c}/minItems`,error:`Array has too few items (${e.length} < ${ac}).`});let N=e.length,$=0,L=!1;if(oc!==void 0){let E=`${c}/prefixItems`,P=Math.min(oc.length,N);for(;$<P;$++){let D=he(e[$],oc[$],r,n,a,i,`${s}/${$}`,`${E}/${$}`);if(d[$]=!0,!D.valid&&(L=a,T.push({instanceLocation:s,keyword:"prefixItems",keywordLocation:E,error:"Items did not match schema."},...D.errors),L))break}}if(So!==void 0){let E=`${c}/items`;if(Array.isArray(So)){let P=Math.min(So.length,N);for(;$<P;$++){let D=he(e[$],So[$],r,n,a,i,`${s}/${$}`,`${E}/${$}`);if(d[$]=!0,!D.valid&&(L=a,T.push({instanceLocation:s,keyword:"items",keywordLocation:E,error:"Items did not match schema."},...D.errors),L))break}}else for(;$<N;$++){let P=he(e[$],So,r,n,a,i,`${s}/${$}`,E);if(d[$]=!0,!P.valid&&(L=a,T.push({instanceLocation:s,keyword:"items",keywordLocation:E,error:"Items did not match schema."},...P.errors),L))break}if(!L&&Hp!==void 0){let P=`${c}/additionalItems`;for(;$<N;$++){let D=he(e[$],Hp,r,n,a,i,`${s}/${$}`,P);d[$]=!0,D.valid||(L=a,T.push({instanceLocation:s,keyword:"additionalItems",keywordLocation:P,error:"Items did not match additional items schema."},...D.errors))}}}if(Bp!==void 0)if(N===0&&Ht===void 0)T.push({instanceLocation:s,keyword:"contains",keywordLocation:`${c}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(Ht!==void 0&&N<Ht)T.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array has less items (${N}) than minContains (${Ht}).`});else{let E=`${c}/contains`,P=T.length,D=0;for(let j=0;j<N;j++){let Ze=he(e[j],Bp,r,n,a,i,`${s}/${j}`,E);Ze.valid?(d[j]=!0,D++):T.push(...Ze.errors)}D>=(Ht||0)&&(T.length=P),Ht===void 0&&Ba===void 0&&D===0?T.splice(P,0,{instanceLocation:s,keyword:"contains",keywordLocation:E,error:"Array does not contain item matching schema."}):Ht!==void 0&&D<Ht?T.push({instanceLocation:s,keyword:"minContains",keywordLocation:`${c}/minContains`,error:`Array must contain at least ${Ht} items matching schema. Only ${D} items were found.`}):Ba!==void 0&&D>Ba&&T.push({instanceLocation:s,keyword:"maxContains",keywordLocation:`${c}/maxContains`,error:`Array may contain at most ${Ba} items matching schema. ${D} items were found.`})}if(!L&&Lp!==void 0){let E=`${c}/unevaluatedItems`;for($;$<N;$++){if(d[$])continue;let P=he(e[$],Lp,r,n,a,i,`${s}/${$}`,E);d[$]=!0,P.valid||T.push({instanceLocation:s,keyword:"unevaluatedItems",keywordLocation:E,error:"Items did not match unevaluated items schema."},...P.errors)}}if(Aw)for(let E=0;E<N;E++){let P=e[E],D=typeof P=="object"&&P!==null;for(let j=0;j<N;j++){if(E===j)continue;let Ze=e[j];(P===Ze||D&&(typeof Ze=="object"&&Ze!==null)&&co(P,Ze))&&(T.push({instanceLocation:s,keyword:"uniqueItems",keywordLocation:`${c}/uniqueItems`,error:`Duplicate items at indexes ${E} and ${j}.`}),E=Number.MAX_SAFE_INTEGER,j=Number.MAX_SAFE_INTEGER)}}}else if(l==="number"){if(r==="4"?(Nr!==void 0&&(vo===!0&&e<=Nr||e<Nr)&&T.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${vo?"or equal to ":""} ${Nr}.`}),jr!==void 0&&(_o===!0&&e>=jr||e>jr)&&T.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${_o?"or equal to ":""} ${jr}.`})):(Nr!==void 0&&e<Nr&&T.push({instanceLocation:s,keyword:"minimum",keywordLocation:`${c}/minimum`,error:`${e} is less than ${Nr}.`}),jr!==void 0&&e>jr&&T.push({instanceLocation:s,keyword:"maximum",keywordLocation:`${c}/maximum`,error:`${e} is greater than ${jr}.`}),vo!==void 0&&e<=vo&&T.push({instanceLocation:s,keyword:"exclusiveMinimum",keywordLocation:`${c}/exclusiveMinimum`,error:`${e} is less than ${vo}.`}),_o!==void 0&&e>=_o&&T.push({instanceLocation:s,keyword:"exclusiveMaximum",keywordLocation:`${c}/exclusiveMaximum`,error:`${e} is greater than or equal to ${_o}.`})),Ga!==void 0){let N=e%Ga;Math.abs(0-N)>=11920929e-14&&Math.abs(Ga-N)>=11920929e-14&&T.push({instanceLocation:s,keyword:"multipleOf",keywordLocation:`${c}/multipleOf`,error:`${e} is not a multiple of ${Ga}.`})}}else if(l==="string"){let N=Va===void 0&&Fa===void 0?0:vv(e);Va!==void 0&&N<Va&&T.push({instanceLocation:s,keyword:"minLength",keywordLocation:`${c}/minLength`,error:`String is too short (${N} < ${Va}).`}),Fa!==void 0&&N>Fa&&T.push({instanceLocation:s,keyword:"maxLength",keywordLocation:`${c}/maxLength`,error:`String is too long (${N} > ${Fa}).`}),Gp!==void 0&&!new RegExp(Gp,"u").test(e)&&T.push({instanceLocation:s,keyword:"pattern",keywordLocation:`${c}/pattern`,error:"String does not match pattern."}),sr!==void 0&&np[sr]&&!np[sr](e)&&T.push({instanceLocation:s,keyword:"format",keywordLocation:`${c}/format`,error:`String does not match format "${sr}".`})}return{valid:T.length===0,errors:T}}o(he,"validate");var Es=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=rr(t)}validate(t){return he(t,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(t,r){r&&(t={...t,$id:r}),rr(t,this.lookup)}};var uo=class{static{o(this,"CfWorkerJsonSchemaValidator")}constructor(t){this.shortcircuit=t?.shortcircuit??!0,this.draft=t?.draft??"2020-12"}getValidator(t){let r=new Es(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 iO,context as Us,propagation as wv,SpanKind as bv,SpanStatusCode as op,trace as Oa}from"@opentelemetry/api";var sO="mcp-gateway",cO="mcp-gateway",uO=Dr,dO="2.0",Rv=Oa.getTracer(sO),ap=iO.getMeter(cO),lO=ap.createHistogram("mcp.client.operation.duration",{description:"The duration of the MCP request or notification as observed on the sender.",unit:"s"}),pO=ap.createHistogram("mcp.server.operation.duration",{description:"MCP request or notification duration as observed on the receiver.",unit:"s"}),mO=ap.createHistogram("mcp.client.session.duration",{description:"The duration of the MCP session as observed on the MCP client.",unit:"s"}),fO=["traceparent","tracestate","baggage"];function ip(){return performance.now()/1e3}o(ip,"nowSeconds");function Cv(e,t){t(Math.max(ip()-e,0))}o(Cv,"recordDurationSeconds");function _v(e){return e===void 0?void 0:String(e)}o(_v,"stringifyAttribute");function Ne(e,t,r){r!==void 0&&(e[t]=r)}o(Ne,"assignAttribute");function hO(e){if(e.capabilityType==="tool"||e.capabilityType==="prompt")return e.capabilityName}o(hO,"readTargetName");function Iv(e){let t=hO({kind:"client",...e});return t?`${e.methodName} ${t}`:e.methodName}o(Iv,"buildMcpOperationSpanName");function sp(e){let t={"mcp.method.name":e.methodName};return Ne(t,"jsonrpc.protocol.version",e.jsonRpcProtocolVersion??dO),Ne(t,"jsonrpc.request.id",_v(e.jsonRpcRequestId)),Ne(t,"mcp.protocol.version",e.mcpProtocolVersion??uO),Ne(t,"mcp.session.id",e.mcpSessionId),Ne(t,"mcp.resource.uri",e.resourceUri),Ne(t,"rpc.response.status_code",_v(e.rpcResponseStatusCode)),Ne(t,"error.type",e.errorType),e.capabilityType==="tool"&&(Ne(t,"gen_ai.operation.name","execute_tool"),Ne(t,"gen_ai.tool.name",e.capabilityName)),e.capabilityType==="prompt"&&Ne(t,"gen_ai.prompt.name",e.capabilityName),Ne(t,"network.protocol.name",e.networkProtocolName?.toLowerCase()),Ne(t,"network.protocol.version",e.networkProtocolVersion),Ne(t,"network.transport",e.networkTransport),Ne(t,"server.address",e.serverAddress),Ne(t,"server.port",e.serverPort),Ne(t,"client.address",e.clientAddress),Ne(t,"client.port",e.clientPort),t}o(sp,"buildMcpOperationAttributes");function gO(e){let t=sp({methodName:"initialize",...e});return delete t["mcp.method.name"],t}o(gO,"buildMcpSessionAttributes");function Pv(e,t,r){e.setAttribute("error.type",r),e.setStatus({code:op.ERROR}),t instanceof Error&&e.recordException(t)}o(Pv,"setSpanError");function xv(e){let t=e?.code;return typeof t=="string"||typeof t=="number"?String(t):e instanceof Error?e.name:"_OTHER"}o(xv,"readErrorType");function yO(e){let t=e&&typeof e=="object"?e._meta:void 0;return!t||typeof t!="object"?Us.active():wv.extract(Us.active(),t,{get(r,n){let a=r[n];return typeof a=="string"?a:void 0},keys(r){return Object.keys(r)}})}o(yO,"readServerParentContext");function SO(e){let t=Oa.getSpanContext(Us.active()),r=Oa.getSpanContext(e);if(!(!t||!Oa.isSpanContextValid(t))&&!(r&&Oa.isSpanContextValid(r)&&t.traceId===r.traceId&&t.spanId===r.spanId))return[{context:t}]}o(SO,"readAmbientSpanLink");function kv(e){return e&&typeof e=="object"&&e.isError===!0?"tool_error":void 0}o(kv,"readResultErrorType");async function Ur(e,t){let r=ip(),n=sp({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});return Rv.startActiveSpan(Iv(e),{kind:bv.CLIENT,attributes:n},async a=>{try{let i=await t(),s=kv(i);return s&&(a.setAttribute("error.type",s),a.setStatus({code:op.ERROR}),n["error.type"]=s),i}catch(i){let s=e.errorType??xv(i);throw n["error.type"]=s,Pv(a,i,s),i}finally{Cv(r,i=>{lO.record(i,n)}),a.end()}})}o(Ur,"runMcpClientOperation");async function Or(e,t){let r=ip(),n=yO(e.params),a=sp({kind:"server",networkProtocolName:"http",networkTransport:"tcp",...e}),i=SO(n);return Rv.startActiveSpan(Iv(e),{kind:bv.SERVER,attributes:a,...i?{links:i}:{}},n,async s=>{try{let c=await t(),d=kv(c);return d&&(s.setAttribute("error.type",d),s.setStatus({code:op.ERROR}),a["error.type"]=d),c}catch(c){let d=e.errorType??xv(c);throw a["error.type"]=d,Pv(s,c,d),c}finally{Cv(r,c=>{pO.record(c,a)}),s.end()}})}o(Or,"runMcpServerOperation");function Tv(e){let t={...e??{},_meta:{...e?._meta&&typeof e._meta=="object"?e._meta:{}}};return wv.inject(Us.active(),t._meta,{set(r,n,a){fO.includes(n)&&(r[n]=a)}}),t}o(Tv,"injectMcpTraceContextIntoParams");function Av(e,t){let r=gO({kind:"client",networkProtocolName:"http",networkTransport:"tcp",...e});mO.record(Math.max(t,0),r)}o(Av,"recordMcpClientSessionDuration");var Os=class{static{o(this,"ExperimentalClientTasks")}constructor(t){this._client=t}async*callToolStream(t,r=hr,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 x(A.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 x(A.InvalidParams,`Structured content does not match the tool's output schema: ${l.errorMessage}`)};return}}catch(l){if(l instanceof x){yield{type:"error",error:l};return}yield{type:"error",error:new x(A.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 $s(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&&$s(i,r[a])}}if(Array.isArray(e.anyOf))for(let r of e.anyOf)typeof r!="boolean"&&$s(r,t);if(Array.isArray(e.oneOf))for(let r of e.oneOf)typeof r!="boolean"&&$s(r,t)}}o($s,"applyElicitationDefaults");function vO(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(vO,"getSupportedElicitationModes");var Ms=class extends Gn{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",Ru,t.tools,async()=>(await this.listTools()).tools),t.prompts&&this._serverCapabilities?.prompts?.listChanged&&this._setupListChangedHandler("prompts",_u,t.prompts,async()=>(await this.listPrompts()).prompts),t.resources&&this._serverCapabilities?.resources?.listChanged&&this._setupListChangedHandler("resources",lu,t.resources,async()=>(await this.listResources()).resources)}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=Bi(this._capabilities,t)}setRequestHandler(t,r){let a=Bn(t)?.method;if(!a)throw new Error("Schema is missing a method literal");let i;if(br(a)){let c=a;i=c._zod?.def?.value??c.value}else{let c=a;i=c._def?.value??c.value}if(typeof i!="string")throw new Error("Schema method literal must be a string");let s=i;if(s==="elicitation/create"){let c=o(async(d,p)=>{let l=Ge(Pu,d);if(!l.success){let b=l.error instanceof Error?l.error.message:String(l.error);throw new x(A.InvalidParams,`Invalid elicitation request: ${b}`)}let{params:m}=l.data;m.mode=m.mode??"form";let{supportsFormMode:h,supportsUrlMode:y}=vO(this._capabilities.elicitation);if(m.mode==="form"&&!h)throw new x(A.InvalidParams,"Client does not support form-mode elicitation requests");if(m.mode==="url"&&!y)throw new x(A.InvalidParams,"Client does not support URL-mode elicitation requests");let v=await Promise.resolve(r(d,p));if(m.task){let b=Ge(Zt,v);if(!b.success){let R=b.error instanceof Error?b.error.message:String(b.error);throw new x(A.InvalidParams,`Invalid task creation result: ${R}`)}return b.data}let S=Ge(gr,v);if(!S.success){let b=S.error instanceof Error?S.error.message:String(S.error);throw new x(A.InvalidParams,`Invalid elicitation result: ${b}`)}let _=S.data,w=m.mode==="form"?m.requestedSchema:void 0;if(m.mode==="form"&&_.action==="accept"&&_.content&&w&&this._capabilities.elicitation?.form?.applyDefaults)try{$s(w,_.content)}catch{}return _},"wrappedHandler");return super.setRequestHandler(t,c)}if(s==="sampling/createMessage"){let c=o(async(d,p)=>{let l=Ge(Iu,d);if(!l.success){let _=l.error instanceof Error?l.error.message:String(l.error);throw new x(A.InvalidParams,`Invalid sampling request: ${_}`)}let{params:m}=l.data,h=await Promise.resolve(r(d,p));if(m.task){let _=Ge(Zt,h);if(!_.success){let w=_.error instanceof Error?_.error.message:String(_.error);throw new x(A.InvalidParams,`Invalid task creation result: ${w}`)}return _.data}let v=m.tools||m.toolChoice?Do:Gr,S=Ge(v,h);if(!S.success){let _=S.error instanceof Error?S.error.message:String(S.error);throw new x(A.InvalidParams,`Invalid sampling result: ${_}`)}return S.data},"wrappedHandler");return super.setRequestHandler(t,c)}return super.setRequestHandler(t,r)}assertCapability(t,r){if(!this._serverCapabilities?.[t])throw new Error(`Server does not support ${t} (required for ${r})`)}async connect(t,r){if(await super.connect(t),t.sessionId===void 0)try{let n=await this.request({method:"initialize",params:{protocolVersion:pr,capabilities:this._capabilities,clientInfo:this._clientInfo}},ru,r);if(n===void 0)throw new Error(`Server sent invalid initialize result: ${n}`);if(!mr.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){xs(this._serverCapabilities?.tasks?.requests,t,"Server")}assertTaskHandlerCapability(t){this._capabilities&&ks(this._capabilities.tasks?.requests,t,"Client")}async ping(t){return this.request({method:"ping"},Ft,t)}async complete(t,r){return this.request({method:"completion/complete",params:t},xu,r)}async setLoggingLevel(t,r){return this.request({method:"logging/setLevel",params:{level:t}},Ft,r)}async getPrompt(t,r){return this.request({method:"prompts/get",params:t},vu,r)}async listPrompts(t,r){return this.request({method:"prompts/list",params:t},mu,r)}async listResources(t,r){return this.request({method:"resources/list",params:t},au,r)}async listResourceTemplates(t,r){return this.request({method:"resources/templates/list",params:t},su,r)}async readResource(t,r){return this.request({method:"resources/read",params:t},du,r)}async subscribeResource(t,r){return this.request({method:"resources/subscribe",params:t},Ft,r)}async unsubscribeResource(t,r){return this.request({method:"resources/unsubscribe",params:t},Ft,r)}async callTool(t,r=hr,n){if(this.isToolTaskRequired(t.name))throw new x(A.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 x(A.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 x(A.InvalidParams,`Structured content does not match the tool's output schema: ${s.errorMessage}`)}catch(s){throw s instanceof x?s:new x(A.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},bu,r);return this.cacheToolMetadata(n.tools),n}_setupListChangedHandler(t,r,n,a){let i=Xf.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 zs(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}o(zs,"normalizeHeaders");function Ev(e=fetch,t){return t?async(r,n)=>{let a={...t,...n,headers:n?.headers?{...zs(t.headers),...zs(n.headers)}:t.headers};return e(r,a)}:e}o(Ev,"createFetchWithInit");var qs=class extends Error{static{o(this,"ParseError")}constructor(t,r){super(t),this.name="ParseError",this.type=r.type,this.field=r.field,this.value=r.value,this.line=r.line}};function cp(e){}o(cp,"noop");function Uv(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");let{onEvent:t=cp,onError:r=cp,onRetry:n=cp,onComment:a}=e,i="",s=!0,c,d="",p="";function l(S){let _=s?S.replace(/^\xEF\xBB\xBF/,""):S,[w,b]=_O(`${i}${_}`);for(let R of w)m(R);i=b,s=!1}o(l,"feed");function m(S){if(S===""){y();return}if(S.startsWith(":")){a&&a(S.slice(S.startsWith(": ")?2:1));return}let _=S.indexOf(":");if(_!==-1){let w=S.slice(0,_),b=S[_+1]===" "?2:1,R=S.slice(_+b);h(w,R,S);return}h(S,"",S)}o(m,"parseLine");function h(S,_,w){switch(S){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 qs(`Invalid \`retry\` value: "${_}"`,{type:"invalid-retry",value:_,line:w}));break;default:r(new qs(`Unknown field "${S.length>20?`${S.slice(0,20)}\u2026`:S}"`,{type:"unknown-field",field:S,value:_,line:w}));break}}o(h,"processField");function y(){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(y,"dispatchEvent");function v(S={}){i&&S.consume&&m(i),s=!0,c=void 0,d="",p="",i=""}return o(v,"reset"),{feed:l,reset:v}}o(Uv,"createParser");function _O(e){let t=[],r="",n=0;for(;n<e.length;){let a=e.indexOf("\r",n),i=e.indexOf(`
|
|
57
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]===`
|
|
58
|
-
`&&n++}}return[t,r]}o(mO,"splitLines");var zs=class extends TransformStream{static{o(this,"EventSourceParserStream")}constructor({onError:t,onRetry:r,onComment:n}={}){let a;super({start(i){a=bv({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 fO={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}},Ms=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=wv(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??fO}async _authThenStart(){if(!this._authProvider)throw new Ft("No auth provider");let t;try{t=await hr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})}catch(r){throw this.onerror?.(r),r}if(t!=="AUTHORIZED")throw new Ft;return await this._startOrAuthSse({resumptionToken:void 0})}async _commonHeaders(){let t={};if(this._authProvider){let n=await this._authProvider.tokens();n&&(t.Authorization=`Bearer ${n.access_token}`)}this._sessionId&&(t["mcp-session-id"]=this._sessionId),this._protocolVersion&&(t["mcp-protocol-version"]=this._protocolVersion);let r=Os(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(y=>{this._serverRetryMs=y},"onRetry")})).getReader();for(;;){let{value:y,done:v}=await l.read();if(v)break;if(y.id&&(s=y.id,c=!0,a?.(y.id)),!!y.data&&(!y.event||y.event==="message"))try{let S=Dr.parse(JSON.parse(y.data));gt(S)&&(d=!0,i!==void 0&&(S.id=i)),this.onmessage?.(S)}catch(S){this.onerror?.(S)}}(n||c)&&!d&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:a,replayMessageId:i},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(n||c)&&!d&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:a,replayMessageId:i},0)}catch(y){this.onerror?.(new Error(`Failed to reconnect: ${y instanceof Error?y.message:String(y)}`))}}},"processStream")()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new Ft("No auth provider");if(await hr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ft("Failed to authorize")}async close(){this._reconnectionTimeout&&(clearTimeout(this._reconnectionTimeout),this._reconnectionTimeout=void 0),this._abortController?.abort(),this.onclose?.()}async send(t,r){try{let{resumptionToken:n,onresumptiontoken:a}=r||{};if(n){this._startOrAuthSse({resumptionToken:n,replayMessageId:It(t)?t.id:void 0}).catch(h=>this.onerror?.(h));return}let i=await this._commonHeaders();i.set("content-type","application/json"),i.set("accept","application/json, text/event-stream");let s={...this._requestInit,method:"POST",headers:i,body:JSON.stringify(t),signal:this._abortController?.signal},c=await(this._fetch??fetch)(this._url,s),d=c.headers.get("mcp-session-id");if(d&&(this._sessionId=d),!c.ok){let h=await c.text().catch(()=>null);if(c.status===401&&this._authProvider){if(this._hasCompletedAuthFlow)throw new kr(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:y,scope:v}=nd(c);if(this._resourceMetadataUrl=y,this._scope=v,await hr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new Ft;return this._hasCompletedAuthFlow=!0,this.send(t)}if(c.status===403&&this._authProvider){let{resourceMetadataUrl:y,scope:v,error:S}=nd(c);if(S==="insufficient_scope"){let _=c.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===_)throw new kr(403,"Server returned 403 after trying upscoping");if(v&&(this._scope=v),y&&(this._resourceMetadataUrl=y),this._lastUpscopingHeader=_??void 0,await hr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new Ft;return this.send(t)}}throw new kr(c.status,`Error POSTing to endpoint: ${h}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,c.status===202){await c.body?.cancel(),Nf(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(h=>this.onerror?.(h));return}let l=(Array.isArray(t)?t:[t]).filter(h=>"method"in h&&"id"in h&&h.id!==void 0).length>0,m=c.headers.get("content-type");if(l)if(m?.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:a},!1);else if(m?.includes("application/json")){let h=await c.json(),y=Array.isArray(h)?h.map(v=>Dr.parse(v)):[Dr.parse(h)];for(let v of y)this.onmessage?.(v)}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 Rv(e=[]){let t={};for(let r of e){if(!r.value){if(r.required)throw g("internal_server_error",`Native MCP transport header ${r.name} is required but has no value configured.`);continue}t[r.name]=r.value}return t}o(Rv,"resolveNativeMcpRequestHeaders");var hO={name:"zuplo-mcp-gateway",version:"0.1.0"},gO=new io({draft:"7",shortcircuit:!1}),yO=5,SO=500,Pv=3e4,vO=2*1024*1024,_O=2;function Cv(){return performance.now()/1e3}o(Cv,"nowSeconds");function wO(e){if(e.port)return Number(e.port);if(e.protocol==="https:")return 443;if(e.protocol==="http:")return 80}o(wO,"readServerPort");function bO(e,t){return{mcpSessionId:t,serverAddress:e.hostname,serverPort:wO(e)}}o(bO,"buildNativeMcpOperationContext");function an(e){return vv(e)}o(an,"withTraceMeta");function qs(e){if(e>SO)throw g("upstream_import_failed","Upstream import exceeded the maximum allowed capability count.")}o(qs,"assertImportedCapabilityBudget");function Iv(e){return Object.keys(e).length===0?{}:{requestInit:{headers:e}}}o(Iv,"buildRequestInit");function RO(e){return(t,r)=>Mn(t,r,{additionalCrossOriginStrippedHeaders:e,maxRedirects:_O,maxResponseBytes:vO,problemCode:"upstream_capability_invocation_failed",timeoutMs:Pv})}o(RO,"createNativeMcpFetch");function CO(e){return new Promise((t,r)=>{let n=setTimeout(()=>{r(g("upstream_capability_invocation_failed","Upstream MCP request exceeded the maximum allowed time."))},Pv);e.then(a=>{clearTimeout(n),t(a)},a=>{clearTimeout(n),r(a)})})}o(CO,"withNativeMcpRequestTimeout");function IO(e,t=[]){let r=Rv(t),n=e?.type==="headers"?Object.keys(e.headers):[],a=[...Object.keys(r),...n],i={fetch:RO(a)};if(!e)return{...i,...Iv(r)};switch(e.type){case"mcp_oauth_provider":return{authProvider:e.provider,...i,...Iv(r)};case"bearer_token":return{...i,requestInit:{headers:{...r,Authorization:`Bearer ${e.token}`}}};case"headers":return{...i,requestInit:{headers:{...r,...e.headers}}}}}o(IO,"buildNativeMcpTransportOptions");async function sn(e,t,r){let{transport:n}=De(e),a=new URL(n.baseUrl),i=new Ms(a,IO(r,n.requestHeaders)),s=new Us(hO,{capabilities:{},jsonSchemaValidator:gO});return CO((async()=>{let c=Cv();await s.connect(i);let d=i.sessionId,p=bO(a,d);try{return await t(s,p)}finally{if(i.sessionId)try{await i.terminateSession()}catch{}await s.close(),d&&_v(p,Cv()-c)}})())}o(sn,"withNativeMcpClient");async function PO(e,t,r){let n=[],a,i=0;do{if(i>=yO)throw g("upstream_capability_invocation_failed",`${e} pagination exceeded the maximum allowed page count.`);let s=await t(a);i+=1,n.push(...r(s)),a=s.nextCursor}while(a);return n}o(PO,"collectPaginatedSdkItems");async function Ns(e){return e.enabled?PO(e.label,e.fetchPage,e.readItems):[]}o(Ns,"listNativeMcpCapabilityItems");async function xv(e){return sn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Pr({methodName:"tools/list",...r},()=>Ns({enabled:!!n?.tools,label:"Tool list",fetchPage:o(i=>t.listTools(an(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.tools,"readItems")}));return qs(a.length),{tools:a}},e.credential)}o(xv,"listNativeMcpTools");async function kv(e){return sn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Pr({methodName:"prompts/list",...r},()=>Ns({enabled:!!n?.prompts,label:"Prompt list",fetchPage:o(i=>t.listPrompts(an(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.prompts,"readItems")}));return qs(a.length),{prompts:a}},e.credential)}o(kv,"listNativeMcpPrompts");async function Tv(e){return sn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Pr({methodName:"resources/list",...r},()=>Ns({enabled:!!n?.resources,label:"Resource list",fetchPage:o(i=>t.listResources(an(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.resources,"readItems")}));return qs(a.length),{resources:a}},e.credential)}o(Tv,"listNativeMcpResources");async function Av(e){return sn(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Pr({methodName:"resources/templates/list",...r},()=>Ns({enabled:!!n?.resources,label:"Resource template list",fetchPage:o(i=>t.listResourceTemplates(an(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.resourceTemplates,"readItems")}));return qs(a.length),{resourceTemplates:a}},e.credential)}o(Av,"listNativeMcpResourceTemplates");async function Ev(e){return sn(e.upstreamServerId,(t,r)=>Pr({methodName:"tools/call",capabilityType:"tool",capabilityName:e.params.name,...r},async()=>await t.callTool(an(e.params))),e.credential)}o(Ev,"callNativeMcpTool");async function Uv(e){return sn(e.upstreamServerId,(t,r)=>Pr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:e.params.name,...r},()=>t.getPrompt(an(e.params))),e.credential)}o(Uv,"getNativeMcpPrompt");async function Ov(e){return sn(e.upstreamServerId,(t,r)=>Pr({methodName:"resources/read",capabilityType:"resource",resourceUri:e.params.uri,...r},()=>t.readResource(an(e.params))),e.credential)}o(Ov,"readNativeMcpResource");var so=class extends x{static{o(this,"ConnectRequiredMcpError")}constructor(t){super(E.InvalidRequest,t.message),this.name="ConnectRequiredMcpError"}};function xO(e){return{content:[{type:"text",text:e}],isError:!0}}o(xO,"buildToolErrorResult");function kO(e){return e.authUrl?new Ht([{mode:"url",elicitationId:crypto.randomUUID(),message:e.message,url:e.authUrl}],e.message):new so(e)}o(kO,"toConnectRequiredError");function TO(e){return{credentialType:e.type,...e.type==="headers"?{headerNames:Object.keys(e.headers).sort()}:{}}}o(TO,"buildCredentialResolvedAttributes");function AO(e){V(e.context,{eventType:B.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:TO(e.credential)})}o(AO,"emitCredentialResolvedAnalyticsEvent");function EO(e){if(V(e.context,{eventType:B.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")V(e.context,{eventType:B.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=UO(e.payload.state);V(e.context,{eventType:B.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(EO,"emitCredentialMissingAnalyticsEvent");function UO(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required";default:{let t=e;return"connect_required"}}}o(UO,"connectRequiredReasonCode");function OO(e){return e.ownerMode==="none"?JSON.stringify(["none",e.upstreamServerId,e.authProfileId]):qr({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId})}o(OO,"readRouteBindingCredentialCacheKey");function Nv(e){if(e.ownerMode!=="none")return{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}}o(Nv,"readOwnedRouteBindingLookup");async function $O(e){let t=Gc(e.request);if(!t)return new Map;let r=new Map;for(let s of e.routeBindings){let c=Nv(s);c!==void 0&&r.set(qr(c),c)}if(r.size===0)return new Map;let n=[...r.values()],a=await K().authorizeAndLoadConnections({accessTokenHash:await le(t),resource:zr(e.virtualServerId,e.request.url),virtualServerId:e.virtualServerId,upstreamConnectionKeys:n,now:re(new Date)});if(a.kind!=="authorized")return new Map;let i=new Map;return a.upstreamConnections.forEach((s,c)=>{let d=n[c];d!==void 0&&i.set(qr(d),s.connection)}),i}o($O,"preloadCompositeAuthorizedConnections");function zO(e){let t=new Map;return r=>{let n=OO(r),a=t.get(n);if(a)return a;let i=(async()=>{let s=await e.preloadedConnections,c=Nv(r),d=c===void 0?void 0:qr(c),p=await Ni({request:e.request,routeAuth:r,...d!==void 0&&s.has(d)?{preloadedConnection:s.get(d)}:{}});if(p.kind==="connect_required")throw EO({context:e.context,payload:p.payload,routeBinding:r}),kO(p.payload);return AO({context:e.context,credential:p.credential,routeBinding:r}),p.credential})();return t.set(n,i),i}}o(zO,"createCredentialResolver");var $v=500;function dp(e){return e.length<=$v?e:`${e.slice(0,$v)}...`}o(dp,"truncateAnalyticsDetail");function MO(e){V(e.context,{eventType:B.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(MO,"emitToolInvocationCompletedAnalyticsEvent");function up(e){V(e.context,{eventType:B.MCP_CAPABILITY_INVOKED,outcome:"success",routeBinding:e.routeBinding,mcpMethod:e.mcpMethod,capabilityName:e.capabilityName,capabilityType:e.capabilityType})}o(up,"emitCapabilityInvokedAnalyticsEvent");function zv(e){let t={};typeof e.itemCount=="number"&&(t.itemCount=e.itemCount),e.errorDetail!==void 0&&(t.detail=dp(e.errorDetail)),V(e.context,{eventType:B.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(zv,"emitCapabilityListedAnalyticsEvent");function Mv(e){V(e.context,{eventType:B.MCP_CAPABILITY_COMPLETED,outcome:"success",routeBinding:e.routeBinding,mcpMethod:e.mcpMethod,capabilityName:e.capabilityName,capabilityType:e.capabilityType,latencyMs:e.latencyMs})}o(Mv,"emitCapabilityCompletedAnalyticsEvent");function qv(e){let t=e.error instanceof Error?e.error.message:String(e.error),r=e.error instanceof Ht||e.error instanceof so,n=e.error instanceof x&&e.error.code===E.InvalidParams,a=r?B.MCP_CAPABILITY_CONNECT_REQUIRED:B.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";V(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:dp(t)}})}o(qv,"emitCapabilityFailedAnalyticsEvent");function qO(e){return e instanceof Ht||e instanceof so?{eventType:B.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required"}:e instanceof x&&e.code===E.InvalidParams?{eventType:B.MCP_CAPABILITY_FAILED,outcome:"failure",reasonCode:"invalid_tool_arguments",reasonClass:"client",errorType:"tool_error",mcpErrorType:"InvalidParams"}:{eventType:B.MCP_CAPABILITY_FAILED,outcome:"failure",reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"tool_error"}}o(qO,"classifyToolInvocationFailure");function NO(e){let t=e.error instanceof Error?e.error.message:String(e.error),r=qO(e.error);V(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:dp(t)}})}o(NO,"emitToolInvocationFailedAnalyticsEvent");var DO=256*1024;function jO(e){if(e.arguments===void 0)return;let t;try{t=new TextEncoder().encode(JSON.stringify(e.arguments)).length}catch{throw new x(E.InvalidParams,"Tool arguments must be JSON-serializable.")}if(t>DO)throw new x(E.InvalidParams,"Tool arguments exceed the maximum allowed size.")}o(jO,"assertToolArgumentsWithinLimit");function lp(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 x(E.InvalidRequest,`Published item ${e.capabilityName} on virtual server ${e.virtualServerId} is claimed by ${t.length} upstream bindings.`);return t[0]}o(lp,"findBindingForPublishedCapability");function cn(e){let t=e.routeBindings[0];if(e.routeBindings.length!==1||t===void 0)throw new x(E.InternalError,`Upstream MCP catalog mode for virtual server ${e.publishedVirtualServer.virtualServerId} requires exactly one upstream binding.`);return t}o(cn,"requireSingleTransparentBinding");function HO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:cn(e),upstreamName:e.toolName};let t=e.publishedVirtualServer.catalog.tools.find(r=>r.name===e.toolName&&r.enabled!==!1);if(!t)throw new x(E.MethodNotFound,`Tool ${e.toolName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:lp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(HO,"resolvePublishedToolRoute");function LO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:cn(e),upstreamName:e.promptName};let t=e.publishedVirtualServer.catalog.prompts.find(r=>r.name===e.promptName&&r.enabled!==!1);if(!t)throw new x(E.MethodNotFound,`Prompt ${e.promptName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:lp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(LO,"resolvePublishedPromptRoute");function BO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:cn(e),upstreamUri:e.resourceUri};let t=e.publishedVirtualServer.catalog.resources.find(r=>r.uri===e.resourceUri&&r.enabled!==!1);if(!t)throw new x(E.MethodNotFound,`Resource ${e.resourceUri} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:lp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamUri:t.upstreamUri}}o(BO,"resolvePublishedResourceRoute");function Dv(e){let t=$O({request:e.request,routeBindings:e.routeBindings,virtualServerId:e.publishedVirtualServer.virtualServerId}),r=zO({context:e.context,preloadedConnections:t,request:e.request}),n=e.publishedVirtualServer.virtualServerId;async function a(i){let s=Date.now();try{let c=await i.invoke();return zv({context:e.context,routeBinding:i.routeBinding,virtualServerName:n,capabilityType:i.capabilityType,mcpMethod:i.mcpMethod,outcome:"success",itemCount:i.countItems(c),latencyMs:Date.now()-s}),c}catch(c){let d=c instanceof Error?c.message:String(c);throw zv({context:e.context,routeBinding:i.routeBinding,virtualServerName:n,capabilityType:i.capabilityType,mcpMethod:i.mcpMethod,outcome:"failure",latencyMs:Date.now()-s,reasonCode:"upstream_capability_list_failed",reasonClass:"upstream",errorType:"capability_list_error",errorDetail:d}),c}}return o(a,"listCapability"),{async listTools(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return a({capabilityType:"tool",mcpMethod:"tools/list",invoke:o(async()=>({tools:e.publishedVirtualServer.catalog.tools.filter(s=>s.enabled!==!1).map(Ri)}),"invoke"),countItems:o(s=>s.tools.length,"countItems")});let i=cn(e);return a({capabilityType:"tool",mcpMethod:"tools/list",routeBinding:i,invoke:o(async()=>xv({upstreamServerId:i.upstreamServerId,credential:await r(i)}),"invoke"),countItems:o(s=>s.tools.length,"countItems")})},async callTool(i){let s=HO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,toolName:i.name});up({context:e.context,routeBinding:s.binding,capabilityType:"tool",capabilityName:i.name,mcpMethod:"tools/call"});let c=Date.now();try{jO(i);let d=await r(s.binding),p=await Ev({upstreamServerId:s.binding.upstreamServerId,params:{...i,name:s.upstreamName},credential:d});return MO({context:e.context,routeBinding:s.binding,toolName:i.name,result:p,latencyMs:Date.now()-c}),e.context.log.debug({event:"upstream_tool_invocation_succeeded",toolName:i.name,upstreamName:s.upstreamName,upstreamServerId:s.binding.upstreamServerId,authProfileId:s.binding.authProfileId,isError:p.isError===!0},"Upstream tool invocation completed"),p}catch(d){if(NO({context:e.context,routeBinding:s.binding,toolName:i.name,error:d,latencyMs:Date.now()-c}),d instanceof Ht||d instanceof so)throw e.context.log.info({event:"upstream_tool_invocation_connect_required",toolName:i.name,upstreamServerId:s.binding.upstreamServerId,authProfileId:s.binding.authProfileId,ownerMode:s.binding.ownerMode,hasAuthUrl:d instanceof Ht},"Upstream tool invocation requires user to complete a connect flow"),d;let p={event:"upstream_tool_invocation_failed",code:"upstream_capability_invocation_failed",toolName:i.name,upstreamName:s.upstreamName,upstreamServerId:s.binding.upstreamServerId,authProfileId:s.binding.authProfileId};return d instanceof x&&(p.mcpErrorCode=d.code),d instanceof Error?(p.errorName=d.name,p.errorMessage=d.message,d.cause instanceof Error&&(p.causeName=d.cause.name,p.causeMessage=d.cause.message)):p.errorMessage=String(d),e.context.log.warn(p,"Upstream tool invocation failed; returning generic gateway error to MCP client"),xO(Ke("upstream_capability_invocation_failed").publicDetail)}},async listPrompts(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return a({capabilityType:"prompt",mcpMethod:"prompts/list",invoke:o(async()=>({prompts:e.publishedVirtualServer.catalog.prompts.filter(s=>s.enabled!==!1).map(Ci)}),"invoke"),countItems:o(s=>s.prompts.length,"countItems")});let i=cn(e);return a({capabilityType:"prompt",mcpMethod:"prompts/list",routeBinding:i,invoke:o(async()=>kv({upstreamServerId:i.upstreamServerId,credential:await r(i)}),"invoke"),countItems:o(s=>s.prompts.length,"countItems")})},async getPrompt(i){let s=LO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,promptName:i.name});up({context:e.context,routeBinding:s.binding,capabilityType:"prompt",capabilityName:i.name,mcpMethod:"prompts/get"});let c=Date.now();try{let d=await Uv({upstreamServerId:s.binding.upstreamServerId,params:{...i,name:s.upstreamName},credential:await r(s.binding)});return Mv({context:e.context,routeBinding:s.binding,capabilityType:"prompt",capabilityName:i.name,mcpMethod:"prompts/get",latencyMs:Date.now()-c}),d}catch(d){throw qv({context:e.context,routeBinding:s.binding,capabilityType:"prompt",capabilityName:i.name,mcpMethod:"prompts/get",error:d,latencyMs:Date.now()-c}),d}},async listResources(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return a({capabilityType:"resource",mcpMethod:"resources/list",invoke:o(async()=>({resources:e.publishedVirtualServer.catalog.resources.filter(s=>s.enabled!==!1).map(Ii)}),"invoke"),countItems:o(s=>s.resources.length,"countItems")});let i=cn(e);return a({capabilityType:"resource",mcpMethod:"resources/list",routeBinding:i,invoke:o(async()=>Tv({upstreamServerId:i.upstreamServerId,credential:await r(i)}),"invoke"),countItems:o(s=>s.resources.length,"countItems")})},async listResourceTemplates(){if(e.publishedVirtualServer.catalog.catalogSource==="openapi")return{resourceTemplates:[]};let i=cn(e);return Av({upstreamServerId:i.upstreamServerId,credential:await r(i)})},async readResource(i){let s=BO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,resourceUri:i.uri});up({context:e.context,routeBinding:s.binding,capabilityType:"resource",capabilityName:i.uri,mcpMethod:"resources/read"});let c=Date.now();try{let d=await Ov({upstreamServerId:s.binding.upstreamServerId,params:{...i,uri:s.upstreamUri},credential:await r(s.binding)});return Mv({context:e.context,routeBinding:s.binding,capabilityType:"resource",capabilityName:i.uri,mcpMethod:"resources/read",latencyMs:Date.now()-c}),d}catch(d){throw qv({context:e.context,routeBinding:s.binding,capabilityType:"resource",capabilityName:i.uri,mcpMethod:"resources/read",error:d,latencyMs:Date.now()-c}),d}}}}o(Dv,"createCapabilityDispatcher");var GO="0.1.0",Hv="POST",VO="POST, OPTIONS",FO=new io({draft:"7",shortcircuit:!1});function pp(e){return Response.json({jsonrpc:"2.0",id:null,error:{code:-32e3,message:e}},{status:405,headers:{Allow:Hv}})}o(pp,"jsonRpcMethodNotAllowedResponse");function ZO(e){let t={Allow:Hv},r=e.headers.get("origin"),n=e.headers.get("access-control-request-method");if(r&&n){t["Access-Control-Allow-Methods"]=VO;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(ZO,"buildOptionsResponse");function un(e){let t=e&&typeof e=="object"?e.id:void 0;return typeof t=="string"||typeof t=="number"?t:void 0}o(un,"readJsonRpcRequestId");function Ds(e){return e&&typeof e=="object"?e.params:void 0}o(Ds,"readMcpRequestParams");function jv(e,t){return e.headers.get(t)??void 0}o(jv,"readMcpHeader");function KO(e){return{mcpProtocolVersion:jv(e,"mcp-protocol-version")??$r,mcpSessionId:jv(e,"mcp-session-id")}}o(KO,"buildServerTelemetryBase");function JO(e){if(e.headers.has("mcp-protocol-version"))return e;let t=new Headers(e.headers);return t.set("mcp-protocol-version",$r),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(JO,"ensureProtocolVersionHeader");async function mp(e,t){if(e.method==="OPTIONS")return ZO(e);if(e.method==="GET")return pp("Standalone SSE GET is not supported by this stateless virtual MCP server. Use POST streamable HTTP for MCP requests.");if(e.method==="DELETE")return pp("Session termination via DELETE is not supported because this virtual MCP server is stateless.");if(e.method!=="POST")return pp("Only POST is supported by this virtual MCP server.");let r=wn(t),n=Mr(r.virtualServerId),a=Di(t);if(n.catalog.catalogSource==="upstream_mcp"&&a.length!==1)throw t.log.error({event:"virtual_server_binding_count_invalid",code:"internal_server_error",virtualServerId:r.virtualServerId,bindingCount:a.length,catalogSource:n.catalog.catalogSource},"MCP virtual server route requires exactly one upstream binding"),g("internal_server_error",`MCP virtual server route requires exactly one upstream binding; found ${a.length}.`);let i=KO(e),s=Dv({context:t,publishedVirtualServer:n,request:e,routeBindings:a}),c=ie(e.url),d=new xs({enableDnsRebindingProtection:!0,allowedOrigins:[c]}),p=new Ps(n.catalog.serverInfo??{name:r.virtualServerId,version:GO},{capabilities:{prompts:{},resources:{},tools:{}},jsonSchemaValidator:FO});p.setRequestHandler(_u,async m=>xr({methodName:"tools/list",params:Ds(m),jsonRpcRequestId:un(m),...i},()=>s.listTools())),p.setRequestHandler(Mo,async m=>xr({methodName:"tools/call",capabilityType:"tool",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:un(m),...i},()=>s.callTool(m.params))),p.setRequestHandler(lu,async m=>xr({methodName:"prompts/list",params:Ds(m),jsonRpcRequestId:un(m),...i},()=>s.listPrompts())),p.setRequestHandler(mu,async m=>xr({methodName:"prompts/get",capabilityType:"prompt",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:un(m),...i},()=>s.getPrompt(m.params))),p.setRequestHandler(nu,async m=>xr({methodName:"resources/list",params:Ds(m),jsonRpcRequestId:un(m),...i},()=>s.listResources())),p.setRequestHandler(au,async m=>xr({methodName:"resources/templates/list",params:Ds(m),jsonRpcRequestId:un(m),...i},()=>s.listResourceTemplates())),p.setRequestHandler(cu,async m=>xr({methodName:"resources/read",capabilityType:"resource",resourceUri:m.params.uri,params:m.params,jsonRpcRequestId:un(m),...i},()=>s.readResource(m.params))),await p.connect(d);let l=await d.handleRequest(e);return JO(l)}o(mp,"virtualServerHandler");async function WO(e,t){return Rt("handler.mcp-virtual-server"),mp(e,t)}o(WO,"McpVirtualServerHandler");function YO(e){let t=Pt(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(YO,"buildRouteAuthBaseFromConnection");function Bv(e){if(!e.connection.authProfiles[e.authMode])throw g("internal_server_error",`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`);let r=Pt(e.authMode);return{upstreamServerId:e.connection.id,virtualServerId:e.virtualServerId,authProfileId:$n(e.connection.id,e.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.authMode,ownerMode:r.ownerMode}}o(Bv,"buildRouteAuthBaseFromPolicyOptions");function Gv(e,t){let n=yt().byVirtualServerId.get(t);if(!n)throw g("unknown_virtual_server",`Unknown virtual server: ${t}`);let a=n.connections.find(i=>i.upstreamServerId===e);if(!a)throw g("virtual_server_upstream_mismatch",`Virtual server ${t} does not bind upstream ${e}.`);return YO({connection:a,virtualServerId:t})}o(Gv,"resolveRouteAuthBase");function Lv(e,t){switch(e){case"user":return ir(t.subjectId);case"shared":return ni()}}o(Lv,"buildOwnerForPrincipal");function js(e,t){switch(e.ownerMode){case"shared":return{...e,owner:Lv(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:Lv(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"none":return e}}o(js,"resolveRouteAuthForPrincipal");function QO(e){let t=Object.keys(e.connection.authProfiles);if(t.length!==1)throw g("internal_server_error",`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];if(r===void 0)throw g("internal_server_error",`Upstream policy ${e.policyName} does not declare an auth mode.`);return Za.parse(r)}o(QO,"readSingleAuthMode");async function fp(e,t,r,n){let a=QO({policyName:n,connection:r}),i=wn(t),s=Bv({connection:r,virtualServerId:i.virtualServerId,authMode:a});if(s.ownerMode==="none")return cd(t,{...s,connectionPolicyName:n}),e;let c=Pm(t);return cd(t,{...js(s,c),connectionPolicyName:n}),e}o(fp,"mcpUpstreamConnectionPolicy");var hp=class extends vn{static{o(this,"McpUpstreamConnectionInboundPolicy")}#t;constructor(t,r){let n=bi(t,r);super(n,r),this.#t=n}async handler(t,r){return Rt("policy.inbound.mcp-upstream-connection"),fp(t,r,this.#t,this.policyName)}};ae();var Vv="application/json",XO="application/x-www-form-urlencoded";function e$(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(e$,"normalizeContentType");function t$(e,t){return e===t?!0:t===Vv&&e.endsWith("+json")}o(t$,"contentTypeMatches");function r$(e,t){if(!t||t.length===0)return;let r=e$(e.headers.get("content-type"));if(!t.some(n=>t$(r,n)))throw g("invalid_request",`Request body must be ${t.join(" or ")}.`)}o(r$,"assertExpectedContentType");function n$(e,t,r){let n=e.headers.get("content-length");if(!n)return;let a=Number.parseInt(n,10);if(Number.isFinite(a)&&a>t)throw g("invalid_request",`${r} exceeded the maximum allowed size.`)}o(n$,"assertContentLengthWithinLimit");async function Fv(e,t){let r=t.label??"Request body";r$(e,t.expectedContentTypes),n$(e,t.maxBytes,r);let n=await xi(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>g("invalid_request",`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o(Fv,"readBoundedTextBody");async function Zv(e,t){let r=await Fv(e,{...t,expectedContentTypes:[Vv]});try{return JSON.parse(r)}catch(n){throw g("invalid_request","Request body must be valid JSON.",n)}}o(Zv,"readBoundedJsonBody");async function Hs(e,t){let r=await Fv(e,{...t,expectedContentTypes:[XO]});return new URLSearchParams(r)}o(Hs,"readBoundedFormUrlEncodedBody");var Kv=Symbol("Html");function o$(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}o(o$,"escapeHtml");function a$(e){return e===null||typeof e!="object"?!1:e[Kv]===!0}o(a$,"isHtml");function Jv(e){return e==null||e===!1?"":Array.isArray(e)?e.map(Jv).join(""):a$(e)?e.value:o$(String(e))}o(Jv,"renderValue");function er(e){return{[Kv]:!0,value:e}}o(er,"trustedHtml");var Ua=er("");function ce(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=Jv(t[n]),r+=e[n+1]??"";return er(r)}o(ce,"html");function Tr(e){return e.value}o(Tr,"renderHtml");var tr=er('*,:before,:after{box-sizing:border-box}:root{--bg:#f5f6f8;--surface:#fff;--surface-2:#f8fafc;--border:#e5e7eb;--border-strong:#d1d5db;--text:#0f172a;--text-2:#475569;--text-3:#64748b;--text-muted:#94a3b8;--accent:#0f172a;--accent-hover:#1e293b;--accent-text:#fff;--focus-ring:#0f172a29;--danger:#b91c1c;--danger-bg:#b91c1c0f;--danger-border:#b91c1c38;--warning:#92400e;--warning-bg:#fffbeb;--warning-border:#fde68a;--success:#15803d;--success-bg:#f0fdf4;--success-border:#bbf7d0;--radius-sm:4px;--radius:8px;--radius-lg:12px;--radius-pill:9999px;--shadow-sm:0 1px 2px #0f172a0d;--shadow:0 1px 2px #0f172a0a,0 6px 16px #0f172a0f;--font-sans:-apple-system,BlinkMacSystemFont,"Segoe UI",Inter,system-ui,sans-serif;--font-mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Monaco,Consolas,monospace}@media (prefers-color-scheme:dark){:root{--bg:#0a0c10;--surface:#15171c;--surface-2:#1e2128;--border:#262932;--border-strong:#3a3e48;--text:#fafafa;--text-2:#cbd5e1;--text-3:#94a3b8;--text-muted:#71717a;--accent:#fafafa;--accent-hover:#e4e4e7;--accent-text:#0a0c10;--focus-ring:#fafafa2e;--danger:#f87171;--danger-bg:#f8717114;--danger-border:#f871714d;--warning:#fbbf24;--warning-bg:#fbbf2414;--warning-border:#fbbf2447;--success:#34d399;--success-bg:#34d39914;--success-border:#34d3994d;--shadow-sm:0 1px 2px #0006;--shadow:0 1px 2px #0006,0 8px 24px #0006}}html,body{margin:0;padding:0}body{font-family:var(--font-sans);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;flex-direction:column;justify-content:center;align-items:center;min-height:100dvh;padding:48px 20px;font-size:14px;line-height:1.5;display:flex}.card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius-lg);width:100%;max-width:480px;box-shadow:var(--shadow);overflow:hidden}.card__head{text-align:center;padding:32px 32px 24px}.card__icon{border-radius:var(--radius);background:var(--surface-2);object-fit:contain;border:1px solid var(--border);width:48px;height:48px;margin:0 auto 16px;display:block}.card__title{letter-spacing:-.01em;color:var(--text);margin:0;font-size:20px;font-weight:600;line-height:1.3}.card__subtitle{color:var(--text-2);margin:8px 0 0;font-size:14px;line-height:1.55}.card__subtitle strong{color:var(--text);font-weight:600}.card__description{color:var(--text-3);margin:12px 0 0;font-size:13px;line-height:1.55}.card__principal{color:var(--text-3);background:var(--surface-2);border-radius:var(--radius-pill);text-overflow:ellipsis;white-space:nowrap;align-items:center;gap:6px;max-width:100%;margin:16px 0 0;padding:4px 12px;font-size:12.5px;display:inline-flex;overflow:hidden}.card__body{flex-direction:column;gap:20px;padding:8px 32px 24px;display:flex}.card__head+.card__body{border-top:1px solid var(--border);padding-top:24px}.card__footer{border-top:1px solid var(--border);background:var(--surface-2);flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:8px;padding:16px 24px;display:flex}.card__fineprint{color:var(--text-3);text-align:center;margin:0;font-size:12.5px;line-height:1.5}.card__fineprint strong{color:var(--text-2);font-weight:600}.section-label{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);align-items:baseline;gap:6px;margin:0;font-size:11px;font-weight:600;display:flex}.section-label__count{color:var(--text-3);letter-spacing:0;font-weight:500}.banner{border-radius:var(--radius);border:1px solid;align-items:flex-start;gap:10px;padding:12px 14px;font-size:13px;display:flex}.banner__icon{flex-shrink:0;justify-content:center;align-items:center;width:16px;height:16px;margin-top:1px;display:inline-flex}.banner__body{flex-direction:column;flex:1;gap:2px;min-width:0;display:flex}.banner__title{color:var(--text);margin:0;font-size:13px;font-weight:600}.banner__message{color:var(--text-2);margin:0;font-size:13px;line-height:1.5}.banner--warning{background:var(--warning-bg);border-color:var(--warning-border)}.banner--warning .banner__icon{color:var(--warning)}.banner--alert{background:var(--danger-bg);border-color:var(--danger-border)}.banner--alert .banner__icon,.banner--alert .banner__title{color:var(--danger)}.upstream-list{flex-direction:column;gap:8px;margin:0;padding:0;list-style:none;display:flex}.upstream-card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);flex-direction:column;gap:10px;padding:14px;display:flex}.upstream-card--needs-action{border-color:var(--warning-border);background:var(--warning-bg)}.upstream-card__head{align-items:flex-start;gap:10px;display:flex}.icon-frame{border-radius:var(--radius-sm);border:1px solid var(--border);background:var(--surface-2);width:32px;height:32px;color:var(--text-3);flex-shrink:0;justify-content:center;align-items:center;display:inline-flex;overflow:hidden}.icon-frame img{object-fit:contain;max-width:100%;max-height:100%}.icon-frame--fallback svg{width:18px;height:18px}.inline-icon{object-fit:contain;vertical-align:-2px;border-radius:2px;width:14px;height:14px;margin-right:4px}.upstream-card__main{flex-direction:column;flex:1;gap:3px;min-width:0;display:flex}.upstream-card__title-row{justify-content:space-between;align-items:center;gap:10px;min-width:0;display:flex}.upstream-card__title{color:var(--text);letter-spacing:-.005em;text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;margin:0;font-size:14px;font-weight:600;line-height:1.3;overflow:hidden}.upstream-card__meta{color:var(--text-3);flex-wrap:wrap;align-items:center;gap:6px;font-size:12px;display:flex}.upstream-card__host{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);padding:1px 6px;font-size:11.5px}.upstream-card__sep{color:var(--border-strong)}.upstream-card__description{color:var(--text-2);margin:4px 0 0;font-size:12.5px;line-height:1.5}.status-badge{border-radius:var(--radius-pill);white-space:nowrap;border:1px solid #0000;flex-shrink:0;align-items:center;gap:6px;padding:2px 8px;font-size:11.5px;font-weight:600;display:inline-flex}.status-badge:before{content:"";background:currentColor;border-radius:50%;flex-shrink:0;width:5px;height:5px}.status-badge--success{background:var(--success-bg);color:var(--success);border-color:var(--success-border)}.status-badge--warning{background:var(--warning-bg);color:var(--warning);border-color:var(--warning-border)}.status-badge--neutral{background:var(--surface-2);color:var(--text-2);border-color:var(--border)}.upstream-card__capabilities,.upstream-card__scopes{border-top:1px solid var(--border);margin-top:2px;padding-top:10px}.upstream-card__capabilities--empty{color:var(--text-3);font-size:12px;font-style:italic}.capabilities-summary,.scopes-summary{cursor:pointer;user-select:none;color:var(--text-2);justify-content:space-between;align-items:center;gap:12px;padding:2px 0;font-size:12.5px;list-style:none;display:flex}.capabilities-summary::-webkit-details-marker,.scopes-summary::-webkit-details-marker{display:none}.capabilities-summary:hover,.scopes-summary:hover{color:var(--text)}.capabilities-summary:focus-visible,.scopes-summary:focus-visible{outline:2px solid var(--accent);outline-offset:2px;border-radius:var(--radius-sm)}.capabilities-summary__counts{flex-wrap:wrap;align-items:center;gap:12px;display:flex}.count-pill{color:var(--text-2);align-items:baseline;gap:4px;font-size:12.5px;display:inline-flex}.count-pill__num{font-variant-numeric:tabular-nums;color:var(--text);font-size:13px;font-weight:600}.count-pill--destructive .count-pill__num,.count-pill--destructive .count-pill__label{color:var(--danger)}.capabilities-summary__chevron{color:var(--text-3);flex-shrink:0;transition:transform .15s;display:inline-flex}details[open]>.capabilities-summary .capabilities-summary__chevron,details[open]>.scopes-summary .capabilities-summary__chevron{transform:rotate(180deg)}.capabilities-detail{margin-top:10px}.capability-section{margin-top:14px}.capability-section:first-child{margin-top:6px}.capability-section__title{text-transform:uppercase;letter-spacing:.07em;color:var(--text-3);margin:0 0 6px;font-size:11px;font-weight:600}.capability-list{flex-direction:column;gap:5px;margin:0;padding:0;font-size:12.5px;list-style:none;display:flex}.capability-row{flex-wrap:wrap;align-items:baseline;gap:6px;padding:2px 0;display:flex}.capability-row__name{font-weight:500;font-family:var(--font-mono);color:var(--text);font-size:12.5px}.capability-row__description{color:var(--text-3);flex-basis:100%;font-size:12px;line-height:1.45}.capability-row__description code{font-family:var(--font-mono);background:var(--surface-2);border-radius:var(--radius-sm);color:var(--text-2);padding:1px 4px}.capability-row--more{color:var(--text-3);font-size:12px;font-style:italic}.scopes-list{flex-wrap:wrap;gap:4px;margin-top:8px;display:flex}.scope-chip{font-family:var(--font-mono);background:var(--surface-2);color:var(--text-2);border-radius:var(--radius-sm);border:1px solid var(--border);padding:2px 7px;font-size:11.5px}.badge{border-radius:var(--radius-sm);letter-spacing:.04em;text-transform:uppercase;align-items:center;padding:1px 5px;font-size:10px;font-weight:600;display:inline-flex}.badge--destructive{background:var(--danger-bg);color:var(--danger)}.badge--muted{background:var(--surface-2);color:var(--text-3)}.badge-row{flex-wrap:wrap;gap:4px;display:inline-flex}.muted{color:var(--text-3)}.button{font:inherit;border-radius:var(--radius);cursor:pointer;white-space:nowrap;border:1px solid #0000;justify-content:center;align-items:center;gap:6px;min-height:40px;padding:8px 16px;font-size:14px;font-weight:500;text-decoration:none;transition:background .12s,border-color .12s,color .12s,box-shadow .12s,transform 40ms;display:inline-flex}.button:active{transform:translateY(1px)}.button:focus-visible{box-shadow:0 0 0 3px var(--focus-ring);outline:0}.button--small{padding:5px 10px;font-size:12.5px}.button--primary{background:var(--accent);color:var(--accent-text);border-color:var(--accent)}.button--primary:hover:not(:disabled):not([aria-disabled=true]){background:var(--accent-hover);border-color:var(--accent-hover)}.button:disabled,.button[aria-disabled=true]{cursor:not-allowed;opacity:.55}.button:disabled:hover,.button[aria-disabled=true]:hover{background:var(--accent);border-color:var(--accent)}.button--secondary{background:var(--surface);color:var(--text);border-color:var(--border-strong)}.button--secondary:hover{background:var(--surface-2);border-color:var(--border-strong)}.button--block{width:100%}.reconnect-action{align-items:center;margin-right:auto;display:inline-flex;position:relative}.reconnect-button{gap:7px}.tooltip{width:16px;height:16px;color:var(--accent);background:color-mix(in srgb,var(--accent)8%,transparent);cursor:help;border:1.5px solid;border-radius:50%;justify-content:center;align-items:center;font-size:10.5px;font-weight:700;line-height:1;display:inline-flex;position:relative}.tooltip:after{content:attr(aria-label);z-index:10;border-radius:var(--radius-sm);background:var(--accent);width:280px;max-width:min(280px,100vw - 48px);color:var(--accent-text);box-shadow:var(--shadow);text-align:left;white-space:normal;opacity:0;pointer-events:none;padding:12px 14px;font-size:13px;font-weight:600;line-height:1.45;transition:opacity .12s;position:absolute;bottom:calc(100% + 12px);left:50%;transform:translate(-50%)}.tooltip:before{content:"";z-index:11;border-left:7px solid #0000;border-right:7px solid #0000;border-top:8px solid var(--accent);opacity:0;pointer-events:none;transition:opacity .12s;position:absolute;bottom:calc(100% + 5px);left:50%;transform:translate(-50%)}.tooltip:hover:after,.tooltip:hover:before,.tooltip:focus-visible:after,.tooltip:focus-visible:before{opacity:1}.form{flex-direction:column;gap:6px;display:flex}.form__label{color:var(--text);margin:8px 0 0;font-size:13px;font-weight:600;display:block}.form__label:first-child{margin-top:0}.form__input{box-sizing:border-box;border:1px solid var(--border-strong);border-radius:var(--radius);width:100%;font:inherit;background:var(--surface);color:var(--text);padding:9px 12px;font-size:14px;transition:border-color .12s,box-shadow .12s}.form__input:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--focus-ring);outline:0}.form__note{color:var(--text-3);margin:4px 0 0;font-size:12.5px;line-height:1.5}.form__submit{margin-top:8px}.empty{text-align:center;color:var(--text-3);border:1px dashed var(--border);border-radius:var(--radius);background:var(--surface);padding:24px 16px;font-size:13px}.actions{gap:8px;margin:0;display:flex}@media (width<=480px){body{padding:0}.card{box-shadow:none;border-left:0;border-right:0;border-radius:0;min-height:100dvh}.card__head{padding:24px 20px 16px}.card__body{padding:16px 20px}.card__footer{flex-direction:column-reverse;align-items:stretch;padding:14px 20px}.card__footer .button{width:100%}.reconnect-action{justify-content:center;width:100%;margin-right:0}.reconnect-action .button{flex:1}.tooltip:after{left:auto;right:0;transform:none}}@media (prefers-reduced-motion:reduce){*{transition:none!important}}');function rr(e){return ce`<!doctype html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="referrer" content="no-referrer" /><meta name="robots" content="noindex" /><title>${e.title}</title><link rel="icon" href="${e.iconHref}" /><style>
|
|
56
|
+
`&&n++}}return[t,r]}o(_O,"splitLines");var Ns=class extends TransformStream{static{o(this,"EventSourceParserStream")}constructor({onError:t,onRetry:r,onComment:n}={}){let a;super({start(i){a=Uv({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 wO={initialReconnectionDelay:1e3,maxReconnectionDelay:3e4,reconnectionDelayGrowFactor:1.5,maxRetries:2},$r=class extends Error{static{o(this,"StreamableHTTPError")}constructor(t,r){super(`Streamable HTTP error: ${r}`),this.code=t}},js=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=Ev(r?.fetch,r?.requestInit),this._sessionId=r?.sessionId,this._reconnectionOptions=r?.reconnectionOptions??wO}async _authThenStart(){if(!this._authProvider)throw new wt("No auth provider");let t;try{t=await wr(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 wt;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=zs(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 $r(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 Ns({onRetry:o(y=>{this._serverRetryMs=y},"onRetry")})).getReader();for(;;){let{value:y,done:v}=await l.read();if(v)break;if(y.id&&(s=y.id,c=!0,a?.(y.id)),!!y.data&&(!y.event||y.event==="message"))try{let S=Br.parse(JSON.parse(y.data));_t(S)&&(d=!0,i!==void 0&&(S.id=i)),this.onmessage?.(S)}catch(S){this.onerror?.(S)}}(n||c)&&!d&&this._abortController&&!this._abortController.signal.aborted&&this._scheduleReconnection({resumptionToken:s,onresumptiontoken:a,replayMessageId:i},0)}catch(l){if(this.onerror?.(new Error(`SSE stream disconnected: ${l}`)),(n||c)&&!d&&this._abortController&&!this._abortController.signal.aborted)try{this._scheduleReconnection({resumptionToken:s,onresumptiontoken:a,replayMessageId:i},0)}catch(y){this.onerror?.(new Error(`Failed to reconnect: ${y instanceof Error?y.message:String(y)}`))}}},"processStream")()}async start(){if(this._abortController)throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");this._abortController=new AbortController}async finishAuth(t){if(!this._authProvider)throw new wt("No auth provider");if(await wr(this._authProvider,{serverUrl:this._url,authorizationCode:t,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new wt("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:Tt(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 $r(401,"Server returned 401 after successful authentication");let{resourceMetadataUrl:y,scope:v}=nd(c);if(this._resourceMetadataUrl=y,this._scope=v,await wr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetchWithInit})!=="AUTHORIZED")throw new wt;return this._hasCompletedAuthFlow=!0,this.send(t)}if(c.status===403&&this._authProvider){let{resourceMetadataUrl:y,scope:v,error:S}=nd(c);if(S==="insufficient_scope"){let _=c.headers.get("WWW-Authenticate");if(this._lastUpscopingHeader===_)throw new $r(403,"Server returned 403 after trying upscoping");if(v&&(this._scope=v),y&&(this._resourceMetadataUrl=y),this._lastUpscopingHeader=_??void 0,await wr(this._authProvider,{serverUrl:this._url,resourceMetadataUrl:this._resourceMetadataUrl,scope:this._scope,fetchFn:this._fetch})!=="AUTHORIZED")throw new wt;return this.send(t)}}throw new $r(c.status,`Error POSTing to endpoint: ${h}`)}if(this._hasCompletedAuthFlow=!1,this._lastUpscopingHeader=void 0,c.status===202){await c.body?.cancel(),Ff(t)&&this._startOrAuthSse({resumptionToken:void 0}).catch(h=>this.onerror?.(h));return}let l=(Array.isArray(t)?t:[t]).filter(h=>"method"in h&&"id"in h&&h.id!==void 0).length>0,m=c.headers.get("content-type");if(l)if(m?.includes("text/event-stream"))this._handleSseStream(c.body,{onresumptiontoken:a},!1);else if(m?.includes("application/json")){let h=await c.json(),y=Array.isArray(h)?h.map(v=>Br.parse(v)):[Br.parse(h)];for(let v of y)this.onmessage?.(v)}else throw await c.body?.cancel(),new $r(-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 $r(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 Ov(e=[]){let t={};for(let r of e){if(!r.value){if(r.required)throw g("internal_server_error",`Native MCP transport header ${r.name} is required but has no value configured.`);continue}t[r.name]=r.value}return t}o(Ov,"resolveNativeMcpRequestHeaders");var bO={name:"zuplo-mcp-gateway",version:"0.1.0"},RO=new uo({draft:"7",shortcircuit:!1}),CO=5,IO=500,zv=3e4,PO=2*1024*1024,xO=2;function $v(){return performance.now()/1e3}o($v,"nowSeconds");function kO(e){if(e.port)return Number(e.port);if(e.protocol==="https:")return 443;if(e.protocol==="http:")return 80}o(kO,"readServerPort");function TO(e,t){return{mcpSessionId:t,serverAddress:e.hostname,serverPort:kO(e)}}o(TO,"buildNativeMcpOperationContext");function dn(e){return Tv(e)}o(dn,"withTraceMeta");function Ds(e){if(e>IO)throw g("upstream_import_failed","Upstream import exceeded the maximum allowed capability count.")}o(Ds,"assertImportedCapabilityBudget");function Mv(e){return Object.keys(e).length===0?{}:{requestInit:{headers:e}}}o(Mv,"buildRequestInit");function AO(e){return(t,r)=>Dn(t,r,{additionalCrossOriginStrippedHeaders:e,maxRedirects:xO,maxResponseBytes:PO,problemCode:"upstream_capability_invocation_failed",timeoutMs:zv})}o(AO,"createNativeMcpFetch");function EO(e){return new Promise((t,r)=>{let n=setTimeout(()=>{r(g("upstream_capability_invocation_failed","Upstream MCP request exceeded the maximum allowed time."))},zv);e.then(a=>{clearTimeout(n),t(a)},a=>{clearTimeout(n),r(a)})})}o(EO,"withNativeMcpRequestTimeout");function UO(e,t=[]){let r=Ov(t),n=e?.type==="headers"?Object.keys(e.headers):[],a=[...Object.keys(r),...n],i={fetch:AO(a)};if(!e)return{...i,...Mv(r)};switch(e.type){case"mcp_oauth_provider":return{authProvider:e.provider,...i,...Mv(r)};case"bearer_token":return{...i,requestInit:{headers:{...r,Authorization:`Bearer ${e.token}`}}};case"headers":return{...i,requestInit:{headers:{...r,...e.headers}}}}}o(UO,"buildNativeMcpTransportOptions");async function ln(e,t,r){let{transport:n}=De(e),a=new URL(n.baseUrl),i=new js(a,UO(r,n.requestHeaders)),s=new Ms(bO,{capabilities:{},jsonSchemaValidator:RO});return EO((async()=>{let c=$v();await s.connect(i);let d=i.sessionId,p=TO(a,d);try{return await t(s,p)}finally{await s.close(),d&&Av(p,$v()-c)}})())}o(ln,"withNativeMcpClient");async function OO(e,t,r){let n=[],a,i=0;do{if(i>=CO)throw g("upstream_capability_invocation_failed",`${e} pagination exceeded the maximum allowed page count.`);let s=await t(a);i+=1,n.push(...r(s)),a=s.nextCursor}while(a);return n}o(OO,"collectPaginatedSdkItems");async function Hs(e){return e.enabled?OO(e.label,e.fetchPage,e.readItems):[]}o(Hs,"listNativeMcpCapabilityItems");async function qv(e){return ln(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Ur({methodName:"tools/list",...r},()=>Hs({enabled:!!n?.tools,label:"Tool list",fetchPage:o(i=>t.listTools(dn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.tools,"readItems")}));return Ds(a.length),{tools:a}},e.credential)}o(qv,"listNativeMcpTools");async function Nv(e){return ln(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Ur({methodName:"prompts/list",...r},()=>Hs({enabled:!!n?.prompts,label:"Prompt list",fetchPage:o(i=>t.listPrompts(dn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.prompts,"readItems")}));return Ds(a.length),{prompts:a}},e.credential)}o(Nv,"listNativeMcpPrompts");async function jv(e){return ln(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Ur({methodName:"resources/list",...r},()=>Hs({enabled:!!n?.resources,label:"Resource list",fetchPage:o(i=>t.listResources(dn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.resources,"readItems")}));return Ds(a.length),{resources:a}},e.credential)}o(jv,"listNativeMcpResources");async function Dv(e){return ln(e.upstreamServerId,async(t,r)=>{let n=t.getServerCapabilities(),a=await Ur({methodName:"resources/templates/list",...r},()=>Hs({enabled:!!n?.resources,label:"Resource template list",fetchPage:o(i=>t.listResourceTemplates(dn(i?{cursor:i}:void 0)),"fetchPage"),readItems:o(i=>i.resourceTemplates,"readItems")}));return Ds(a.length),{resourceTemplates:a}},e.credential)}o(Dv,"listNativeMcpResourceTemplates");async function Hv(e){return ln(e.upstreamServerId,(t,r)=>Ur({methodName:"tools/call",capabilityType:"tool",capabilityName:e.params.name,...r},async()=>await t.callTool(dn(e.params))),e.credential)}o(Hv,"callNativeMcpTool");async function Lv(e){return ln(e.upstreamServerId,(t,r)=>Ur({methodName:"prompts/get",capabilityType:"prompt",capabilityName:e.params.name,...r},()=>t.getPrompt(dn(e.params))),e.credential)}o(Lv,"getNativeMcpPrompt");async function Bv(e){return ln(e.upstreamServerId,(t,r)=>Ur({methodName:"resources/read",capabilityType:"resource",resourceUri:e.params.uri,...r},()=>t.readResource(dn(e.params))),e.credential)}o(Bv,"readNativeMcpResource");var lo=class extends x{static{o(this,"ConnectRequiredMcpError")}constructor(t){super(A.InvalidRequest,t.message),this.name="ConnectRequiredMcpError"}},$a=class extends x{static{o(this,"GatewayAuthorizationMcpError")}authorizationFailureKind;constructor(t){super(A.InvalidRequest,qO(t)),this.name="GatewayAuthorizationMcpError",this.authorizationFailureKind=t}};function $O(e){return{content:[{type:"text",text:e}],isError:!0}}o($O,"buildToolErrorResult");function Kv(e){return e.authUrl?new Vt([{mode:"url",elicitationId:crypto.randomUUID(),message:e.message,url:e.authUrl}],e.message):new lo(e)}o(Kv,"toConnectRequiredError");function MO(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(MO,"readOAuthAuthorizationUrl");function zO(e,t){return MO(t)===void 0?!1:e instanceof wt||e instanceof Error&&e.message==="Unauthorized"}o(zO,"isOAuthRedirectUnauthorizedError");function qO(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(qO,"readCompositeAuthorizationFailureDetail");function NO(e){return{credentialType:e.type,...e.type==="headers"?{headerNames:Object.keys(e.headers).sort()}:{}}}o(NO,"buildCredentialResolvedAttributes");function jO(e){V(e.context,{eventType:B.MCP_AUTH_UPSTREAM_CREDENTIAL_RESOLVED,outcome:"success",routeBinding:e.routeBinding,attributes:NO(e.credential)})}o(jO,"emitCredentialResolvedAnalyticsEvent");function Jv(e){if(V(e.context,{eventType:B.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")V(e.context,{eventType:B.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=DO(e.payload.state);V(e.context,{eventType:B.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(Jv,"emitCredentialMissingAnalyticsEvent");function DO(e){switch(e){case"admin_connect_required":return"admin_connect_required";case"authenticating":return"connect_required";default:{let t=e;return"connect_required"}}}o(DO,"connectRequiredReasonCode");function HO(e){return e.ownerMode==="none"?JSON.stringify(["none",e.upstreamServerId,e.authProfileId]):lr({owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId})}o(HO,"readRouteBindingCredentialCacheKey");function dp(e){if(e.ownerMode!=="none")return{owner:e.owner,upstreamServerId:e.upstreamServerId,authProfileId:e.authProfileId}}o(dp,"readOwnedRouteBindingLookup");async function LO(e){let t=Gc(e.request);if(!t)return new Map;let r=new Map;for(let s of e.routeBindings){let c=dp(s);c!==void 0&&r.set(lr(c),c)}if(r.size===0)return new Map;let n=[...r.values()],a=await K().authorizeAndLoadConnections({accessTokenHash:await le(t),resource:ur(e.virtualServerId,e.request.url),virtualServerId:e.virtualServerId,upstreamConnectionKeys:n,now:re(new Date)});if(a.kind!=="authorized")throw new $a(a.kind);let i=new Map;return a.upstreamConnections.forEach((s,c)=>{let d=n[c];d!==void 0&&i.set(lr(d),s.connection)}),i}o(LO,"preloadCompositeAuthorizedConnections");function BO(e){let t=new Map;return r=>{let n=HO(r),a=t.get(n);if(a)return a;let i=(async()=>{let s=await e.preloadedConnections,c=dp(r),d=c===void 0?void 0:lr(c),p=await Hi({request:e.request,routeAuth:r,...d!==void 0&&s.has(d)?{preloadedConnection:s.get(d)}:{}});if(p.kind==="connect_required")throw Jv({context:e.context,payload:p.payload,routeBinding:r}),Kv(p.payload);return jO({context:e.context,credential:p.credential,routeBinding:r}),p.credential})();return t.set(n,i),i}}o(BO,"createCredentialResolver");var Gv=500;function lp(e){return e.length<=Gv?e:`${e.slice(0,Gv)}...`}o(lp,"truncateAnalyticsDetail");function GO(e){V(e.context,{eventType:B.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(GO,"emitToolInvocationCompletedAnalyticsEvent");function up(e){V(e.context,{eventType:B.MCP_CAPABILITY_INVOKED,outcome:"success",routeBinding:e.routeBinding,mcpMethod:e.mcpMethod,capabilityName:e.capabilityName,capabilityType:e.capabilityType})}o(up,"emitCapabilityInvokedAnalyticsEvent");function Vv(e){let t={};typeof e.itemCount=="number"&&(t.itemCount=e.itemCount),e.errorDetail!==void 0&&(t.detail=lp(e.errorDetail)),V(e.context,{eventType:B.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(Vv,"emitCapabilityListedAnalyticsEvent");function Fv(e){V(e.context,{eventType:B.MCP_CAPABILITY_COMPLETED,outcome:"success",routeBinding:e.routeBinding,mcpMethod:e.mcpMethod,capabilityName:e.capabilityName,capabilityType:e.capabilityType,latencyMs:e.latencyMs})}o(Fv,"emitCapabilityCompletedAnalyticsEvent");function Zv(e){let t=e.error instanceof Error?e.error.message:String(e.error),r=e.error instanceof Vt||e.error instanceof lo,n=e.error instanceof x&&e.error.code===A.InvalidParams,a=r?B.MCP_CAPABILITY_CONNECT_REQUIRED:B.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";V(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:lp(t)}})}o(Zv,"emitCapabilityFailedAnalyticsEvent");function VO(e){return e instanceof Vt||e instanceof lo?{eventType:B.MCP_CAPABILITY_CONNECT_REQUIRED,outcome:"connect_required",reasonCode:"connect_required",reasonClass:"auth",errorType:"connect_required"}:e instanceof $a?{eventType:B.MCP_CAPABILITY_FAILED,outcome:"denied",reasonCode:`gateway_access_token_${e.authorizationFailureKind}`,reasonClass:"auth",errorType:"auth_error",mcpErrorType:"InvalidRequest"}:e instanceof x&&e.code===A.InvalidParams?{eventType:B.MCP_CAPABILITY_FAILED,outcome:"failure",reasonCode:"invalid_tool_arguments",reasonClass:"client",errorType:"tool_error",mcpErrorType:"InvalidParams"}:{eventType:B.MCP_CAPABILITY_FAILED,outcome:"failure",reasonCode:"upstream_capability_invocation_failed",reasonClass:"upstream",errorType:"tool_error"}}o(VO,"classifyToolInvocationFailure");function FO(e){let t=e.error instanceof Error?e.error.message:String(e.error),r=VO(e.error);V(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:lp(t)}})}o(FO,"emitToolInvocationFailedAnalyticsEvent");var ZO=256*1024;function KO(e){if(e.arguments===void 0)return;let t;try{t=new TextEncoder().encode(JSON.stringify(e.arguments)).length}catch{throw new x(A.InvalidParams,"Tool arguments must be JSON-serializable.")}if(t>ZO)throw new x(A.InvalidParams,"Tool arguments exceed the maximum allowed size.")}o(KO,"assertToolArgumentsWithinLimit");function pp(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 x(A.InvalidRequest,`Published item ${e.capabilityName} on virtual server ${e.virtualServerId} is claimed by ${t.length} upstream bindings.`);return t[0]}o(pp,"findBindingForPublishedCapability");function pn(e){let t=e.routeBindings[0];if(e.routeBindings.length!==1||t===void 0)throw new x(A.InternalError,`Upstream MCP catalog mode for virtual server ${e.publishedVirtualServer.virtualServerId} requires exactly one upstream binding.`);return t}o(pn,"requireSingleTransparentBinding");function JO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:pn(e),upstreamName:e.toolName};let t=e.publishedVirtualServer.catalog.tools.find(r=>r.name===e.toolName&&r.enabled!==!1);if(!t)throw new x(A.MethodNotFound,`Tool ${e.toolName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:pp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(JO,"resolvePublishedToolRoute");function WO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:pn(e),upstreamName:e.promptName};let t=e.publishedVirtualServer.catalog.prompts.find(r=>r.name===e.promptName&&r.enabled!==!1);if(!t)throw new x(A.MethodNotFound,`Prompt ${e.promptName} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:pp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamName:t.upstreamName}}o(WO,"resolvePublishedPromptRoute");function YO(e){if(e.publishedVirtualServer.catalog.catalogSource==="upstream_mcp")return{binding:pn(e),upstreamUri:e.resourceUri};let t=e.publishedVirtualServer.catalog.resources.find(r=>r.uri===e.resourceUri&&r.enabled!==!1);if(!t)throw new x(A.MethodNotFound,`Resource ${e.resourceUri} is not available on virtual server ${e.publishedVirtualServer.virtualServerId}.`);return{binding:pp({capabilityName:String(t.name),routeBindings:e.routeBindings,upstreamPolicyName:t.upstreamPolicyName,virtualServerId:e.publishedVirtualServer.virtualServerId}),upstreamUri:t.upstreamUri}}o(YO,"resolvePublishedResourceRoute");function Wv(e){let t=LO({request:e.request,routeBindings:e.routeBindings,virtualServerId:e.publishedVirtualServer.virtualServerId}),r=BO({context:e.context,preloadedConnections:t,request:e.request}),n=e.publishedVirtualServer.virtualServerId;async function a(c){if(!zO(c.error,c.credential)||c.routeBinding.ownerMode==="none")return;let d=dp(c.routeBinding);if(d===void 0)return;let l=(await t).get(lr(d))?.id,m=c.routeBinding.owner.mode==="shared"?qi({upstreamServerId:c.routeBinding.upstreamServerId,authProfileId:c.routeBinding.authProfileId,upstreamDisplayName:c.routeBinding.upstreamDisplayName,virtualServerId:c.routeBinding.virtualServerId,...l===void 0?{}:{connectionId:l},requiresReconsent:!0}):await vr({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 Jv({context:e.context,payload:m,routeBinding:c.routeBinding}),Kv(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 Vv({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);throw Vv({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}),p}}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(xi)}),"invoke"),countItems:o(d=>d.tools.length,"countItems")});let c=pn(e);return s({capabilityType:"tool",mcpMethod:"tools/list",routeBinding:c,invoke:o(async()=>i({routeBinding:c,invoke:o(d=>qv({upstreamServerId:c.upstreamServerId,credential:d}),"invoke")}),"invoke"),countItems:o(d=>d.tools.length,"countItems")})},async callTool(c){let d=JO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,toolName:c.name});up({context:e.context,routeBinding:d.binding,capabilityType:"tool",capabilityName:c.name,mcpMethod:"tools/call"});let p=Date.now();try{KO(c);let l=await i({routeBinding:d.binding,invoke:o(m=>Hv({upstreamServerId:d.binding.upstreamServerId,params:{...c,name:d.upstreamName},credential:m}),"invoke")});return GO({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(FO({context:e.context,routeBinding:d.binding,toolName:c.name,error:l,latencyMs:Date.now()-p}),l instanceof Vt||l instanceof lo)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 Vt},"Upstream tool invocation requires user to complete a connect flow"),l;if(l instanceof $a)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 x&&(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"),$O(Ke("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(ki)}),"invoke"),countItems:o(d=>d.prompts.length,"countItems")});let c=pn(e);return s({capabilityType:"prompt",mcpMethod:"prompts/list",routeBinding:c,invoke:o(async()=>i({routeBinding:c,invoke:o(d=>Nv({upstreamServerId:c.upstreamServerId,credential:d}),"invoke")}),"invoke"),countItems:o(d=>d.prompts.length,"countItems")})},async getPrompt(c){let d=WO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,promptName:c.name});up({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=>Lv({upstreamServerId:d.binding.upstreamServerId,params:{...c,name:d.upstreamName},credential:m}),"invoke")});return Fv({context:e.context,routeBinding:d.binding,capabilityType:"prompt",capabilityName:c.name,mcpMethod:"prompts/get",latencyMs:Date.now()-p}),l}catch(l){throw Zv({context:e.context,routeBinding:d.binding,capabilityType:"prompt",capabilityName:c.name,mcpMethod:"prompts/get",error:l,latencyMs:Date.now()-p}),l}},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(Ti)}),"invoke"),countItems:o(d=>d.resources.length,"countItems")});let c=pn(e);return s({capabilityType:"resource",mcpMethod:"resources/list",routeBinding:c,invoke:o(async()=>i({routeBinding:c,invoke:o(d=>jv({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=pn(e);return i({routeBinding:c,invoke:o(d=>Dv({upstreamServerId:c.upstreamServerId,credential:d}),"invoke")})},async readResource(c){let d=YO({publishedVirtualServer:e.publishedVirtualServer,routeBindings:e.routeBindings,resourceUri:c.uri});up({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=>Bv({upstreamServerId:d.binding.upstreamServerId,params:{...c,uri:d.upstreamUri},credential:m}),"invoke")});return Fv({context:e.context,routeBinding:d.binding,capabilityType:"resource",capabilityName:c.uri,mcpMethod:"resources/read",latencyMs:Date.now()-p}),l}catch(l){throw Zv({context:e.context,routeBinding:d.binding,capabilityType:"resource",capabilityName:c.uri,mcpMethod:"resources/read",error:l,latencyMs:Date.now()-p}),l}}}}o(Wv,"createCapabilityDispatcher");var QO="0.1.0",Qv="POST",XO="POST, OPTIONS",e$=new uo({draft:"7",shortcircuit:!1});function mp(e){return Response.json({jsonrpc:"2.0",id:null,error:{code:-32e3,message:e}},{status:405,headers:{Allow:Qv}})}o(mp,"jsonRpcMethodNotAllowedResponse");function t$(e){let t={Allow:Qv},r=e.headers.get("origin"),n=e.headers.get("access-control-request-method");if(r&&n){t["Access-Control-Allow-Methods"]=XO;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(t$,"buildOptionsResponse");function mn(e){let t=e&&typeof e=="object"?e.id:void 0;return typeof t=="string"||typeof t=="number"?t:void 0}o(mn,"readJsonRpcRequestId");function Ls(e){return e&&typeof e=="object"?e.params:void 0}o(Ls,"readMcpRequestParams");function Yv(e,t){return e.headers.get(t)??void 0}o(Yv,"readMcpHeader");function r$(e){return{mcpProtocolVersion:Yv(e,"mcp-protocol-version")??Dr,mcpSessionId:Yv(e,"mcp-session-id")}}o(r$,"buildServerTelemetryBase");function n$(e){if(e.headers.has("mcp-protocol-version"))return e;let t=new Headers(e.headers);return t.set("mcp-protocol-version",Dr),new Response(e.body,{status:e.status,statusText:e.statusText,headers:t})}o(n$,"ensureProtocolVersionHeader");async function fp(e,t){if(e.method==="OPTIONS")return t$(e);if(e.method==="GET")return mp("Standalone SSE GET is not supported by this stateless virtual MCP server. Use POST streamable HTTP for MCP requests.");if(e.method==="DELETE")return mp("Session termination via DELETE is not supported because this virtual MCP server is stateless.");if(e.method!=="POST")return mp("Only POST is supported by this virtual MCP server.");let r=In(t),n=Hr(r.virtualServerId),a=Li(t);if(n.catalog.catalogSource==="upstream_mcp"&&a.length!==1)throw t.log.error({event:"virtual_server_binding_count_invalid",code:"internal_server_error",virtualServerId:r.virtualServerId,bindingCount:a.length,catalogSource:n.catalog.catalogSource},"MCP virtual server route requires exactly one upstream binding"),g("internal_server_error",`MCP virtual server route requires exactly one upstream binding; found ${a.length}.`);let i=r$(e),s=Wv({context:t,publishedVirtualServer:n,request:e,routeBindings:a}),c=ae(e.url),d=new As({enableDnsRebindingProtection:!0,allowedOrigins:[c]}),p=new Ts(n.catalog.serverInfo??{name:r.virtualServerId,version:QO},{capabilities:{prompts:{},resources:{},tools:{}},jsonSchemaValidator:e$});p.setRequestHandler(wu,async m=>Or({methodName:"tools/list",params:Ls(m),jsonRpcRequestId:mn(m),...i},()=>s.listTools())),p.setRequestHandler(No,async m=>Or({methodName:"tools/call",capabilityType:"tool",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:mn(m),...i},()=>s.callTool(m.params))),p.setRequestHandler(pu,async m=>Or({methodName:"prompts/list",params:Ls(m),jsonRpcRequestId:mn(m),...i},()=>s.listPrompts())),p.setRequestHandler(fu,async m=>Or({methodName:"prompts/get",capabilityType:"prompt",capabilityName:m.params.name,params:m.params,jsonRpcRequestId:mn(m),...i},()=>s.getPrompt(m.params))),p.setRequestHandler(ou,async m=>Or({methodName:"resources/list",params:Ls(m),jsonRpcRequestId:mn(m),...i},()=>s.listResources())),p.setRequestHandler(iu,async m=>Or({methodName:"resources/templates/list",params:Ls(m),jsonRpcRequestId:mn(m),...i},()=>s.listResourceTemplates())),p.setRequestHandler(uu,async m=>Or({methodName:"resources/read",capabilityType:"resource",resourceUri:m.params.uri,params:m.params,jsonRpcRequestId:mn(m),...i},()=>s.readResource(m.params))),await p.connect(d);let l=await d.handleRequest(e);return n$(l)}o(fp,"virtualServerHandler");async function o$(e,t){return xt("handler.mcp-virtual-server"),fp(e,t)}o(o$,"McpVirtualServerHandler");function a$(e){let t=At(e.connection.authMode);return{upstreamServerId:e.connection.upstreamServerId,virtualServerId:e.virtualServerId,authProfileId:e.connection.authProfileId,upstreamDisplayName:e.connection.config.displayName,authMode:e.connection.authMode,ownerMode:t.ownerMode}}o(a$,"buildRouteAuthBaseFromConnection");function e_(e){if(!e.connection.authProfiles[e.authMode])throw g("internal_server_error",`Upstream connection ${e.connection.id} does not declare auth mode ${e.authMode}.`);let r=At(e.authMode);return{upstreamServerId:e.connection.id,virtualServerId:e.virtualServerId,authProfileId:Nn(e.connection.id,e.authMode),upstreamDisplayName:e.connection.displayName,authMode:e.authMode,ownerMode:r.ownerMode}}o(e_,"buildRouteAuthBaseFromPolicyOptions");function t_(e,t){let n=at().byVirtualServerId.get(t);if(!n)throw g("unknown_virtual_server",`Unknown virtual server: ${t}`);let a=n.connections.find(i=>i.upstreamServerId===e);if(!a)throw g("virtual_server_upstream_mismatch",`Virtual server ${t} does not bind upstream ${e}.`);return a$({connection:a,virtualServerId:t})}o(t_,"resolveRouteAuthBase");function Xv(e,t){switch(e){case"user":return dr(t.subjectId);case"shared":return si()}}o(Xv,"buildOwnerForPrincipal");function Bs(e,t){switch(e.ownerMode){case"shared":return{...e,owner:Xv(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"user":return{...e,owner:Xv(e.ownerMode,t),initiatedBySubjectId:t.subjectId};case"none":return e}}o(Bs,"resolveRouteAuthForPrincipal");function i$(e){let t=Object.keys(e.connection.authProfiles);if(t.length!==1)throw g("internal_server_error",`Upstream policy ${e.policyName} must declare exactly one auth mode; found ${t.length}.`);let r=t[0];if(r===void 0)throw g("internal_server_error",`Upstream policy ${e.policyName} does not declare an auth mode.`);return Qa.parse(r)}o(i$,"readSingleAuthMode");async function hp(e,t,r,n){let a=i$({policyName:n,connection:r}),i=In(t),s=e_({connection:r,virtualServerId:i.virtualServerId,authMode:a});if(s.ownerMode==="none")return cd(t,{...s,connectionPolicyName:n}),e;let c=Em(t);return cd(t,{...Bs(s,c),connectionPolicyName:n}),e}o(hp,"mcpUpstreamConnectionPolicy");var gp=class extends Rn{static{o(this,"McpUpstreamConnectionInboundPolicy")}#t;constructor(t,r){let n=Pi(t,r);super(n,r),this.#t=n}async handler(t,r){return xt("policy.inbound.mcp-upstream-connection"),hp(t,r,this.#t,this.policyName)}};ue();var r_="application/json",s$="application/x-www-form-urlencoded";function c$(e){return(e??"").split(";")[0]?.trim().toLowerCase()??""}o(c$,"normalizeContentType");function u$(e,t){return e===t?!0:t===r_&&e.endsWith("+json")}o(u$,"contentTypeMatches");function d$(e,t){if(!t||t.length===0)return;let r=c$(e.headers.get("content-type"));if(!t.some(n=>u$(r,n)))throw g("invalid_request",`Request body must be ${t.join(" or ")}.`)}o(d$,"assertExpectedContentType");function l$(e,t,r){let n=e.headers.get("content-length");if(!n)return;let a=Number.parseInt(n,10);if(Number.isFinite(a)&&a>t)throw g("invalid_request",`${r} exceeded the maximum allowed size.`)}o(l$,"assertContentLengthWithinLimit");async function n_(e,t){let r=t.label??"Request body";d$(e,t.expectedContentTypes),l$(e,t.maxBytes,r);let n=await Ei(e.body,{maxBytes:t.maxBytes,createLimitError:o(()=>g("invalid_request",`${r} exceeded the maximum allowed size.`),"createLimitError")});return new TextDecoder().decode(n)}o(n_,"readBoundedTextBody");async function o_(e,t){let r=await n_(e,{...t,expectedContentTypes:[r_]});try{return JSON.parse(r)}catch(n){throw g("invalid_request","Request body must be valid JSON.",n)}}o(o_,"readBoundedJsonBody");async function Gs(e,t){let r=await n_(e,{...t,expectedContentTypes:[s$]});return new URLSearchParams(r)}o(Gs,"readBoundedFormUrlEncodedBody");var a_=Symbol("Html");function p$(e){return e.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}o(p$,"escapeHtml");function m$(e){return e===null||typeof e!="object"?!1:e[a_]===!0}o(m$,"isHtml");function i_(e){return e==null||e===!1?"":Array.isArray(e)?e.map(i_).join(""):m$(e)?e.value:p$(String(e))}o(i_,"renderValue");function nr(e){return{[a_]:!0,value:e}}o(nr,"trustedHtml");var Ma=nr("");function se(e,...t){let r=e[0]??"";for(let n=0;n<t.length;n+=1)r+=i_(t[n]),r+=e[n+1]??"";return nr(r)}o(se,"html");function Mr(e){return e.value}o(Mr,"renderHtml");var or=nr('*,: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 ar(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>
|
|
59
57
|
${e.styles}
|
|
60
|
-
</style></head><body><main class="card"><header class="card__head">${e.headerIcon}<h1 class="card__title">${e.heading}</h1>${e.subhead}</header><div class="card__body">${e.body}</div>${e.footer}</main></body></html>`}o(
|
|
61
|
-
once more.</p>`}o(Qv,"renderApiKeyLoginFailure");function Xv(e){return ce`<form class="form" method="post" action="/oauth/api-key-login" autocomplete="off" ><input type="hidden" name="state" value="${e.state}" /><label class="form__label" for="apiKey">API key</label><input class="form__input" id="apiKey" name="apiKey" type="password" required autocomplete="off" /><button class="button button--primary button--block form__submit" type="submit" >Continue</button></form>`}o(Xv,"renderApiKeyLoginForm");var j5=er('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 6.5l4 4 4-4"/></svg>'),H5=er('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="4" width="18" height="7" rx="1.5"/><rect x="3" y="13" width="18" height="7" rx="1.5"/><circle cx="7" cy="7.5" r=".75" fill="currentColor" stroke="none"/><circle cx="7" cy="16.5" r=".75" fill="currentColor" stroke="none"/></svg>');var L5=er('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var s$="text/html; charset=utf-8";function e_(e,t=200){return new Response(Tr(e),{status:t,headers:{"content-type":s$,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(e_,"apiKeyLoginHtmlResponse");function yp(e,t=401){let r=ln(e);return e_(rr({title:"Sign-in failed",iconHref:r,styles:tr,headerIcon:pn({iconHref:r,fallbackIconHref:dn}),heading:"Sign-in failed",subhead:"",body:Qv(),footer:""}),t)}o(yp,"apiKeyLoginFailureResponse");function t_(e,t){let r=ln(e);return e_(rr({title:"Sign in",iconHref:r,styles:tr,headerIcon:pn({iconHref:r,fallbackIconHref:dn}),heading:"Sign in",subhead:ce`<p class="card__subtitle">Enter your API key to continue.</p>`,body:Xv({state:t}),footer:""}))}o(t_,"renderApiKeyLoginForm");ae();ae();import{errors as p_,jwtVerify as m_,SignJWT as f_}from"jose";ae();import{errors as v$,jwtVerify as _$,SignJWT as w$}from"jose";function Ar(e){let t=Pe().browserLogin[e];if(typeof t=="string"&&t.length>0)return t;throw g("internal_server_error",`browserLogin.${e} is required for federated browser login. Set it on the mcp-oauth-inbound policy options.`)}o(Ar,"requireBrowserLoginField");ae();import{createRemoteJWKSet as u$,errors as Oa,jwtVerify as d$}from"jose";var l$=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()}),p$=u.object({error:u.string().min(1).optional(),error_description:u.string().min(1).optional(),error_uri:u.string().min(1).optional()});function m$(e){let t=p$.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(m$,"readIdpErrorFields");function f$(e){return e instanceof Oa.JWTExpired?"expired":e instanceof Oa.JWTClaimValidationFailed?"claim":e instanceof Oa.JWSSignatureVerificationFailed?"signature":e instanceof Oa.JWKSNoMatchingKey?"jwks_no_match":e instanceof Oa.JWTInvalid?"invalid":e instanceof u.ZodError?"schema":"other"}o(f$,"readJwtFailureKind");var h$=u.object({sub:ve,nonce:u.string().min(1)}).catchall(u.unknown()),Sp;function g$(e){return e instanceof Error&&"cause"in e?e.cause:e}o(g$,"readErrorCause");function y$(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(y$,"readRuntimeGatewayCode");function S$(){if(!Sp){let e=Pe();Sp=u$(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return Sp}o(S$,"readFederatedJwks");async function r_(e){let t=Pe(),r=Ar("tokenUrl"),n=Ar("clientId"),a=Ar("clientSecret"),i=new URL("/oauth/callback",ht(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 lh(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=m$(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"),g({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${c.status}${h.idpError?` idp_error=${h.idpError}`:""}${h.idpErrorDescription?` idp_error_description=${h.idpErrorDescription}`:""})`)})}let p=l$.parse(d),l;try{({payload:l}=await d$(p.id_token,S$(),{issuer:t.oidc.issuer,audience:n}))}catch(h){let y={};throw Ye(y,"error",h),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:f$(h),idpHost:st(r),expectedIssuer:t.oidc.issuer,...y},"Federated id_token failed jose verification"),h}if(l.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:st(r),nonceMissingFromIdToken:l.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),g("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let m=h$.parse(l);return Rn({sub:m.sub,data:m},e.requestUrl)}catch(c){let d=ge(c)??y$(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:g("browser_login_verification_failed","Federated browser login callback could not be verified.",g$(c))}}o(r_,"exchangeFederatedAuthorizationCode");var _p="zuplo_mcp_session",n_="HS256",o_="zuplo-mcp-gateway",a_="zuplo-mcp-gateway",b$=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 R$(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(R$,"parseCookieHeader");async function i_(){return xt({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>mr(e,"browser-session"),"derive")})}o(i_,"getBrowserSessionKey");function vp(e){let t=new URL(ie(e)),r=[`${_p}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(vp,"buildBrowserSessionEvictionCookie");function C$(e){let t=new URL(ie(e.requestUrl)),r=[`${_p}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(C$,"serializeSessionCookie");function s_(e={}){return new URL(Ar("url")).origin}o(s_,"readBrowserLoginOrigin");function wp(){return Pe().browserLogin.stateTtlSeconds}o(wp,"readBrowserLoginStateTtlSeconds");function c_(e){if(!e.user)throw g("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return Rn(e.user,e.url)}o(c_,"resolveCurrentRequestPrincipal");async function Ls(e,t={}){let r=R$(e.headers.get("cookie")).get(_p);if(!r)return{};try{let{payload:n}=await _$(r,await i_(),{algorithms:[n_],issuer:o_,audience:a_}),a=b$.parse(n);if(a.browserLoginOrigin!==s_(t))return{evictCookie:vp(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 v$.JWTExpired?{evictCookie:vp(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:vp(e.url)})}}o(Ls,"readBrowserSession");async function $a(e){let t=Pe().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:s_({virtualServerId:e.virtualServerId})};e.principal.roles&&(r.roles=e.principal.roles);let n=await new w$(r).setProtectedHeader({alg:n_,typ:"JWT"}).setIssuer(o_).setAudience(a_).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await i_());return C$({value:n,requestUrl:e.requestUrl,ttlSeconds:t})}o($a,"createBrowserSessionCookie");async function u_(e){throw g("forbidden","API-key browser login is not supported in this gateway.")}o(u_,"resolveApiKeyBrowserLoginPrincipal");async function d_(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await Ls(e.request,t);if(r.principal)return r.principal;let n=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(!n)throw g("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.");return r_({code:n,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}o(d_,"resolveBrowserLoginCallbackPrincipal");function l_(e){let t=Pe().browserLogin,r=new URL(Ar("url")),n=new URL("/oauth/callback",ht(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",Ar("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(l_,"buildBrowserLoginUrl");var I$={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},L=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=I$[t],a){super(r,a),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};var P$=5*60,Bs="HS256",Gs="zuplo-mcp-gateway",Vs="zuplo-mcp-gateway",x$=u.object({purpose:u.literal("gateway_browser_login"),transactionId:ct,stateId:Qa,exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),k$=u.object({purpose:u.literal("gateway_authorization_setup"),transactionId:ct,stateId:Qa,exp:u.number().int().positive(),iat:u.number().int().positive().optional()});async function h_(){return xt({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>mr(e,"browser-login"),"derive")})}o(h_,"getBrowserLoginKey");async function g_(){return xt({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>mr(e,"authorization-csrf"),"derive")})}o(g_,"getCsrfKey");function y_(e){return{now:e.now??new Date,ttlSeconds:wp()}}o(y_,"readPendingTransactionDependencies");function T$(e,t){return e.subjectId===t.subjectId}o(T$,"principalsMatch");function S_(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}o(S_,"toPendingPrincipal");function v_(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,virtualServerId:e.transaction.virtualServerId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:re(e.now),expiresAt:re(Dt(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw g("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:S_(e.principal)}}o(v_,"createTransactionRecord");async function __(e){let{id:t,...r}=e.record,n=await K().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(n.kind){case"started":return n.transaction;case"already_exists":throw g("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new L("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new L("invalid_request","redirect_uri is not registered for the client.")}}o(__,"startPendingTransaction");async function A$(e){return new f_({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:Bs,typ:"JWT"}).setIssuer(Gs).setAudience(Vs).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await h_())}o(A$,"signBrowserLoginState");async function w_(e){return new f_({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Ic()}).setProtectedHeader({alg:Bs,typ:"JWT"}).setIssuer(Gs).setAudience(Vs).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await g_())}o(w_,"signCsrfToken");async function Fs(e){try{let{payload:t}=await m_(e,await h_(),{algorithms:[Bs],issuer:Gs,audience:Vs}),r=x$.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof p_.JWTExpired?g("oauth_state_expired","Browser login state has expired.",t):g("oauth_state_invalid","Browser login state could not be verified.",t)}}o(Fs,"verifyBrowserLoginStateToken");async function bp(e){try{let{payload:t}=await m_(e,await g_(),{algorithms:[Bs],issuer:Gs,audience:Vs});return{transactionId:k$.parse(t).transactionId}}catch(t){throw t instanceof p_.JWTExpired?g("oauth_state_expired","Authorization setup state has expired.",t):g("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(bp,"verifyCsrfToken");function Zs(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(Zs,"pendingStateErrorCode");function b_(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}o(b_,"toPendingAuthorizationGetResult");function E$(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}o(E$,"toPendingAuthorizationAdvanceResult");function R_(e){return e==="principal_mismatch"?"oauth_callback_mismatch":Zs(e==="consumed_already"?"consumed_already":e)}o(R_,"setupDecisionErrorCode");function U$(e){if(e.kind!=="available")throw g(Zs(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}o(U$,"requireAwaitingSetup");function O$(e){if(e.kind!=="available")throw g(Zs(e.kind),"Browser login state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_login")throw g("oauth_state_invalid","Browser login state is not in the login phase.");return e.record}o(O$,"requireAwaitingLogin");function $$(e){if(!T$(e.currentBrowserPrincipal,e.transaction.principal))throw g("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o($$,"requireCurrentPrincipalMatches");async function C_(e){let t=e.now??new Date,r=wp(),n=Cc(),a=Ic(),i=await A$({transactionId:n,stateId:a,ttlSeconds:r}),s=v_({id:n,transaction:e.transaction,currentStateHash:await le(i),phase:"awaiting_login",now:t,ttlSeconds:r});if(s.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");let c=await __({record:s,client:e.transaction.client});if(c.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");return{transaction:c,browserLoginStateToken:i,browserLoginUrl:l_({state:i,nonce:a,virtualServerId:s.virtualServerId,requestUrl:e.requestUrl})}}o(C_,"startAwaitingLogin");async function I_(e){let{now:t,ttlSeconds:r}=y_(e),n=Cc(),a=await w_({transactionId:n,ttlSeconds:r}),i=v_({id:n,transaction:e.transaction,currentStateHash:await le(a),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");let s=await __({record:i,client:e.transaction.client});if(s.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:s,csrfToken:a}}o(I_,"startAwaitingSetup");async function Rp(e){let{now:t,ttlSeconds:r}=y_(e),n=await Fs(e.browserLoginStateToken),a=await w_({transactionId:n.transactionId,ttlSeconds:r}),i=E$(await K().advancePendingAuthorization({transactionId:n.transactionId,expectedPhase:"awaiting_login",currentStateHash:await le(e.browserLoginStateToken),nextStateHash:await le(a),nextPhase:"awaiting_setup",principal:S_(e.principal),now:re(t)}));if(i.kind!=="advanced")throw g(Zs(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:a}}o(Rp,"completeLogin");async function P_(e){let t=e.now??new Date,r=await Fs(e.browserLoginStateToken);return O$(b_(await K().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await le(e.browserLoginStateToken),now:re(t)})))}o(P_,"getAwaitingLogin");async function x_(e){let t=await Cp(e);return $$({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(x_,"getSetup");async function Cp(e){let t=e.now??new Date,r=await bp(e.csrfToken);return U$(b_(await K().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await le(e.csrfToken),now:re(t)})))}o(Cp,"getSetupTransaction");async function z$(e){let t=await bp(e.csrfToken),r=jt(),n=re(Dt(e.now,P$)),a=await K().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await le(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await le(r),authorizationCodeExpiresAt:n,grantId:Sm(),now:re(e.now)});if(a.kind!=="approved")throw g(a.kind==="cancelled"?"oauth_state_invalid":R_(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(z$,"createAuthorizationCodeRedirectWithDecision");async function M$(e){let t=await bp(e.csrfToken),r=await K().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await le(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:re(e.now)});if(r.kind!=="cancelled")throw g(r.kind==="approved"?"oauth_state_invalid":R_(r.kind),"Authorization setup state is invalid, expired, or already used.");return q$({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}o(M$,"createCancelRedirectWithDecision");function q$(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(q$,"buildClientCancelRedirect");async function k_(e){let t=e.now??new Date;return z$({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(k_,"approve");async function T_(e){let t=e.now??new Date;return M$({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(T_,"cancel");ae();var N$=1e4,D$=5*1024,j$=2,H$=90*24*60*60,Ip=["authorization_code","refresh_token"],Pp=["code"],L$=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(Ip)).min(1).max(2).optional(),response_types:u.array(u.enum(Pp)).min(1).max(1).optional(),scope:u.literal(ye).optional(),token_endpoint_auth_method:_c.default("none")});function B$(e){try{let t=new URL(e);return t.protocol==="https:"&&t.pathname!=="/"}catch{return!1}}o(B$,"isCimdClientIdCandidate");function za(e,t="invalid_request"){if(G$(e))throw new L(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new L(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new L(t,"redirect_uris must not include credentials or fragments.");if(!(r.protocol==="https:"||qe(r)))throw new L(t,"redirect_uris must use HTTPS except loopback HTTP redirects for local clients.")}o(za,"assertValidRedirectUri");function G$(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(G$,"hasForbiddenRawRedirectUriCharacter");async function V$(e){let{response:t,json:r}=await ph(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:j$,maxResponseBytes:D$,timeoutMs:N$});if(!t.ok)throw g("invalid_request","CIMD metadata could not be fetched.");let n=ym.parse(r);if(n.client_id!==e.clientId)throw g("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");if(n.token_endpoint_auth_method!=="none")throw g("invalid_request","CIMD clients must use token_endpoint_auth_method none until private_key_jwt is implemented.");return n}o(V$,"fetchCimdMetadata");async function F$(e){let t=Pi(e),r=await V$({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(F$,"resolveCimdClient");async function A_(e,t){let r=Ne.parse(e);if(B$(r)){if(!Pe().gateway.cimdEnabled)throw new L("invalid_client","OAuth client is not registered.");try{return await F$(r)}catch{throw new L("invalid_client","OAuth client is not registered.")}}let n=await K().readClient({clientId:r});if(n.kind==="found"){let a=n.client,i={kind:"dcr",clientId:r,metadata:{client_id:a.clientId,client_name:a.clientName,redirect_uris:a.redirectUris,token_endpoint_auth_method:a.tokenEndpointAuthMethod}};return a.hashedClientSecret&&(i.hashedClientSecret=a.hashedClientSecret),i}throw new L("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}o(A_,"resolveClient");function E_(e,t){if(!e.metadata.redirect_uris.some(r=>vm(r,t)))throw g("invalid_request","redirect_uri is not registered for the client.")}o(E_,"assertRedirectRegistered");function Z$(e){let t=U_(e.grant_types),r=e.response_types??[...Pp];if(!K$(t))throw new L("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!J$(r))throw new L("invalid_client_metadata","response_types must be code.");if(!W$(e.scope))throw new L("invalid_client_metadata",`Only the ${ye} scope is supported.`)}o(Z$,"assertSupportedDcrRequest");function U_(e){return e===void 0?[...Ip]:Array.from(new Set(e))}o(U_,"normalizeGrantTypes");function K$(e){return e.length===0?!1:e.every(t=>Ip.includes(t))}o(K$,"isSupportedGrantTypes");function J$(e){return e.length===Pp.length&&e[0]==="code"}o(J$,"isSupportedResponseTypes");function W$(e){return e===void 0||e===ye}o(W$,"isSupportedDcrScope");function Ma(e){if(e===void 0||e===ye)return ye;throw new L("invalid_request",`Only the ${ye} scope is supported.`)}o(Ma,"assertSupportedOAuthScope");function co(e,t){let r;try{r=new URL(t)}catch{throw new L("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new L("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!qe(r))throw new L("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let n=ie(e),a=oh(),i=a?[...a.byVirtualServerId.values()].find(s=>new URL(s.routePath,n).toString()===t):void 0;if(!i)throw new L("invalid_target","resource must match a published virtual MCP server.");return i}o(co,"resolveResource");async function O_(e){let t;try{t=L$.parse(e)}catch(l){if(l instanceof u.ZodError){let m=l.issues.some(h=>h.path[0]==="redirect_uris");throw new L(m?"invalid_redirect_uri":"invalid_client_metadata",l.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:l})}throw l}Z$(t);for(let l of t.redirect_uris)za(l,"invalid_redirect_uri");let r=new Date,n=Ne.parse(`dcr:${crypto.randomUUID()}`),a=Dt(r,H$),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:U_(t.grant_types),response_types:["code"],scope:ye,token_endpoint_auth_method:t.token_endpoint_auth_method,client_id_issued_at:i},d={clientId:n,clientName:String(c.client_name),redirectUris:t.redirect_uris,tokenEndpointAuthMethod:t.token_endpoint_auth_method,createdAt:re(r),clientExpiresAt:re(a)};if(t.token_endpoint_auth_method!=="none"){let l=jt();d.hashedClientSecret=await le(l),d.clientSecretExpiresAt=re(a),c.client_secret=l,c.client_secret_expires_at=s,c.client_secret_issued_at=i}if((await K().registerClient(d)).kind==="already_exists")throw g("invalid_request","OAuth client is already registered.");return c}o(O_,"registerDownstreamClient");var Y$="data:,",$_=ce`data-submit-once="true" onsubmit="if (this.dataset.submitted === 'true') return false; this.dataset.submitted = 'true'; setTimeout(() => this.querySelectorAll('button').forEach((button) => { button.disabled = true; }), 0);"`,z_=ce`data-activate-once="true" onclick="if (this.dataset.activated === 'true') return false; this.dataset.activated = 'true'; this.setAttribute('aria-disabled', 'true'); this.style.pointerEvents = 'none';"`;function Q$(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(Q$,"safeGatewayConnectHref");function X$(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(X$,"deriveMode");function ez(e){return Yv({state:e.state,submitOnceAttrs:$_,authorizeAttrs:Ua})}o(ez,"renderActions");function xp(e,t,r){for(let n of e){if(n.ownerMode!=="user"||n.status!==r)continue;let a=Q$(n.connectUrl,t);if(a)return a}}o(xp,"firstUserConnectHref");function tz(e){let t=e.connectHref?ce`<a class="button button--primary" href="${e.connectHref}" ${z_}>Connect</a>`:ce`<button class="button button--primary" type="button" disabled aria-disabled="true">Connect</button>`;return ce`<form class="actions" method="post" action="/oauth/setup" ${$_}><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(tz,"renderSetupActions");function rz(e){return e?ce`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${z_}>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>`:Ua}o(rz,"renderReconnectAction");function kp(e){let t=X$(e.upstreams),r=xp(e.upstreams,e.gatewayOrigin,"not_connected"),n=xp(e.upstreams,e.gatewayOrigin,"reconsent_required"),a=xp(e.upstreams,e.gatewayOrigin,"active"),i=t==="setup"?r??n:void 0,s=ce`<p class="card__subtitle">Authorize '<strong>${e.clientDisplayName}</strong>' to access '<strong>${e.virtualServerDisplayName}</strong>' on your behalf?</p>`,c=t==="setup"?ce`<footer class="card__footer">${tz({state:e.state,connectHref:i})}</footer>`:ce`<footer class="card__footer">${rz(a)}${ez({state:e.state})}</footer>`;return Tr(rr({title:`Authorize access \xB7 ${e.virtualServerDisplayName}`,iconHref:Y$,styles:tr,headerIcon:Ua,heading:"MCP Gateway",subhead:Ua,body:s,footer:c}))}o(kp,"renderConsentPage");function nz(e){try{return new URL(e).host}catch{return}}o(nz,"safeUrlHost");function oz(e){if(e.mode==="user-oauth"||e.mode==="shared-oauth")return e.oauth.scopes}o(oz,"readOAuthScopes");function Tp(e){return e!==void 0&&e.length>0}o(Tp,"hasItems");function az(e){let t=e.registeredConnection.config.serverInfo?.icons;if(Tp(t))return t;let r=e.virtualServer.serverInfo?.icons;return e.virtualServer.connections.length===1&&Tp(r)?r:void 0}o(az,"readServerIcons");async function iz(e){if(!(e.returnTo===void 0||!e.isUserOwned))return Lu({requestUrl:e.requestUrl,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:e.registeredConnection.upstreamServerId,authProfileId:e.registeredConnection.authProfileId,virtualServerId:e.virtualServer.virtualServerId,returnTo:e.returnTo})}o(iz,"readConnectUrl");function mn(e,t){return t===void 0?{}:{[e]:t}}o(mn,"optionalRequirementField");function sz(e){return e.isUserOwned?Om(e.connection):{connected:!0,status:"active"}}o(sz,"readSetupConnectionStatus");function cz(e){let t=oz(e);return Tp(t)?t:void 0}o(cz,"readScopesRequested");function uz(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}o(uz,"readUpdatedAt");function dz(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(Ri),prompts:e.virtualServer.catalog.prompts.filter(r=>r.enabled!==!1&&t(r)).map(Ci),resources:e.virtualServer.catalog.resources.filter(r=>r.enabled!==!1&&t(r)).map(Ii)}}o(dz,"readVirtualServerCapabilities");async function lz(e){let{authConfig:t,authMode:r,config:n,upstreamServerId:a,authProfileId:i}=e.registeredConnection,s=ki(r),c=s==="user",d=sz({connection:e.connection,isUserOwned:c}),p=await iz({...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:dz({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer}),...mn("description",n.description),...mn("transportHost",nz(n.transport.baseUrl)),...mn("scopesRequested",cz(t)),...mn("serverIcons",az({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer})),...mn("connectUrl",p),...mn("updatedAt",uz({connectionStatus:d,isUserOwned:c})),...mn("expiresAt",e.connection?.expiresAt)}}o(lz,"buildSetupRequirement");function M_(e){let t=yt().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(M_,"requireVirtualServer");async function Ap(e){let t=M_(e.transaction.virtualServerId),r=ir(e.transaction.principal.subjectId),n=[],a=new Map;for(let c of t.connections)ki(c.authMode)==="user"&&(a.set(c,n.length),n.push({owner:r,upstreamServerId:c.upstreamServerId,authProfileId:c.authProfileId}));let i=await K().batchGetUpstreamConnections(n),s=[];for(let c of t.connections){let d=ki(c.authMode)==="user",p=a.get(c);s.push(await lz({connection:d&&p!==void 0?i[p]:void 0,registeredConnection:c,virtualServer:t,requestUrl:e.requestUrl,returnTo:e.returnTo,transaction:e.transaction,userOwner:r}))}return s}o(Ap,"requirementsForSetup");function pz(e){return e.virtualServer.serverInfo?.title??e.virtualServer.serverInfo?.name??e.virtualServer.virtualServerId}o(pz,"readVirtualServerDisplayName");async function Ep(e){let t=M_(e.transaction.virtualServerId),r=pz({virtualServer:t}),n=await K().readClient({clientId:e.transaction.clientId}),a=n.kind==="found"?n.client:void 0,i={gatewayOrigin:ie(e.requestUrl),virtualServerDisplayName:r,clientDisplayName:a?.clientName??String(e.transaction.clientId),principalLabel:e.transaction.principal.subjectId},s=t.serverInfo?.title;return s!==void 0&&s!==r&&(i.virtualServerDescription=s),i}o(Ep,"consentContext");function q_(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o(q_,"hasUnresolvedUserUpstream");var mz=["mcp_user"],fz="dev-browser-user",hz=["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:Ja,state:u.string().min(1).optional(),scope:u.literal(ye).default(ye)}),yz=u.enum(["continue","approve","cancel"]).default("continue"),Sz=u.object({state:u.string().min(1),decision:yz}),vz=u.object({state:u.string().min(1),apiKey:u.string().min(1)}),fn=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 N_(e){return typeof e=="string"&&e.length>0?e:void 0}o(N_,"readQueryString");function _z(e,t){let r=N_(e.query.resource);if(t===void 0){if(r!==void 0)return r;throw new L("invalid_target",hz)}let n=zr(t,e.url);if(r===void 0||r===n)return n;throw new L("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(_z,"requireAuthorizeResource");async function wz(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await Ls(e,n);if(a.principal)return{principal:a.principal};if(!e.user)return a.evictCookie===void 0?{}:{setCookie:a.evictCookie};let i=c_(e);return{principal:i,setCookie:await $a({principal:i,requestUrl:e.url,virtualServerId:t})}}o(wz,"resolveBrowserPrincipal");async function bz(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await Ls(e,n);if(!a.principal)throw g("authentication_required","Authorization setup requires a current browser session.");return a.principal}o(bz,"requireSetupPrincipal");async function D_(e){let t=await Ap({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:`/oauth/setup?state=${encodeURIComponent(e.csrfToken)}`}),r=await Ep({transaction:e.transaction,requestUrl:e.requestUrl}),n={kind:"setup_page",html:kp({state:e.csrfToken,virtualServerId:e.transaction.virtualServerId,upstreams:t,...r})};return e.setCookie!==void 0&&(n.setCookie=e.setCookie),n}o(D_,"renderSetup");function Rz(e){if(e===void 0)return;let t=e.metadata.token_endpoint_auth_method;if(t==="private_key_jwt")throw new L("invalid_client","OAuth client authentication method is not supported.");return{clientId:e.clientId,clientName:e.metadata.client_name,tokenEndpointAuthMethod:t}}o(Rz,"toAuthorizationTransactionClient");async function Up(e,t={}){let r=gz.parse({...e.query,resource:_z(e,t.virtualServerId),state:N_(e.query.state)}),n=Ma(r.scope);za(r.redirect_uri);let a=new Date,i=Ne.parse(r.client_id),s=await A_(r.client_id,a);E_(s,r.redirect_uri);try{let c=co(e.url,r.resource),d=Rz(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&&V(t.context,{eventType:B.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 y=await C_({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 v={kind:"redirect",location:y.browserLoginUrl};return m!==void 0&&(v.setCookie=m),v}let h=await I_({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&&V(t.context,{eventType:B.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:c.virtualServerId,attributes:{clientId:i,scope:n,responseType:r.response_type,subjectId:l.subjectId}}),D_({transaction:h.transaction,csrfToken:h.csrfToken,requestUrl:e.url,setCookie:m})}catch(c){throw Cz({redirectUri:r.redirect_uri,clientState:r.state,cause:c})}}o(Up,"authorizeDownstreamClient");function Cz(e){if(e.cause instanceof fn)return e.cause;let t=Iz(e.cause);return t?new fn({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}o(Cz,"toDownstreamAuthorizeRedirectError");function Iz(e){if(e instanceof L)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(Iz,"mapToOAuthRedirectError");async function j_(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let p=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,l=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...p===void 0?{}:{idpErrorDescription:p},...l===void 0?{}:{idpErrorUri:l}},"Identity provider redirected browser-login callback with an error"),g("provider_access_denied",p??"The delegated browser login was not completed.")}let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),g("oauth_state_invalid","Browser login callback is missing state.");let a=await Fs(n),i={request:e,stateId:a.stateId};t.context!==void 0&&(i.context=t.context);let s=await d_(i),c=await Rp({browserLoginStateToken:n,principal:s}),d=await D_({transaction:c.transaction,csrfToken:c.csrfToken,requestUrl:e.url});return d.setCookie=await $a({principal:s,requestUrl:e.url,virtualServerId:c.transaction.virtualServerId}),d}o(j_,"completeBrowserLoginCallback");async function H_(e){let t=Pe(),r=new URL(e.url);if(!qe(r))throw g("forbidden","Local browser login is only available on loopback HTTP origins.");let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw g("oauth_state_invalid","Local browser login is missing state.");let a=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:"/oauth/callback",ie(e.url)),i=new URL(ie(e.url)).origin;if(a.origin!==i||a.pathname!=="/oauth/callback")throw g("oauth_callback_mismatch","Local browser login redirect_uri must target this gateway's /oauth/callback route.");a.searchParams.set("state",n);let s={subjectId:ve.parse(fz),roles:mz};return{kind:"redirect",location:a,setCookie:await $a({principal:s,requestUrl:e.url})}}o(H_,"completeLocalDevBrowserLogin");async function L_(e){let t=vz.parse(e.body),r=await P_({browserLoginStateToken:t.state}),n=await u_({apiKey:t.apiKey,virtualServerId:r.virtualServerId}),a=await Rp({browserLoginStateToken:t.state,principal:n});await mg({apiKey:t.apiKey,principal:n,virtualServerId:a.transaction.virtualServerId});let i=new URL("/oauth/setup",ht(e.request.url));return i.searchParams.set("state",a.csrfToken),{kind:"redirect",location:i,setCookie:await $a({principal:n,requestUrl:e.request.url,virtualServerId:a.transaction.virtualServerId})}}o(L_,"completeApiKeyBrowserLogin");function Pz(e){let t=e.method==="POST"?e.body:e.query;return Sz.parse(t)}o(Pz,"readSetupContinueRequest");async function B_(e){let{state:t,decision:r}=Pz({method:e.request.method,query:e.request.query,body:e.body}),n=new Date,a=await Cp({csrfToken:t,now:n}),i=await bz(e.request,a.virtualServerId,e.context);if(r==="cancel")return{kind:"redirect",location:await T_({csrfToken:t,currentBrowserPrincipal:i,now:n})};let s=await x_({csrfToken:t,currentBrowserPrincipal:i,now:n}),c=await Ap({transaction:s,requestUrl:e.request.url,returnTo:`/oauth/setup?state=${encodeURIComponent(t)}`});if(r==="continue"||q_(c)){let d=await Ep({transaction:s,requestUrl:e.request.url});return{kind:"setup_page",html:kp({state:t,virtualServerId:s.virtualServerId,upstreams:c,...d})}}return{kind:"redirect",location:await k_({csrfToken:t,currentBrowserPrincipal:i,now:n})}}o(B_,"continueDownstreamAuthorizeSetup");ae();var xz=new Set(["authorization_code","refresh_token"]),kz=u.discriminatedUnion("grant_type",[u.object({grant_type:u.literal("authorization_code"),code:u.string().min(1),redirect_uri:u.string().min(1),client_id:u.string().min(1).optional(),code_verifier:Wa,resource:u.url().optional(),scope:u.literal(ye).optional(),client_secret:u.string().min(1).optional()}),u.object({grant_type:u.literal("refresh_token"),refresh_token:u.string().min(1),client_id:u.string().min(1).optional(),resource:u.url().optional(),scope:u.literal(ye).optional(),client_secret:u.string().min(1).optional()})]);function Tz(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!xz.has(t)))throw new L("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o(Tz,"assertSupportedGrantType");var Az=u.object({token:u.string().min(1),client_id:u.string().min(1).optional(),token_type_hint:u.string().optional(),client_secret:u.string().min(1).optional()});function G_(){return Pe().gateway.accessTokenTtlSeconds}o(G_,"readAccessTokenTtlSeconds");function Ez(){return Pe().gateway.refreshTokenTtlSeconds}o(Ez,"readRefreshTokenTtlSeconds");function Uz(e,t){let r=G_(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,n);return{expiresAt:re(Dt(e,a)),expiresIn:a}}o(Uz,"calculateAccessTokenExpiresAt");function V_(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new L("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new L("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new L("invalid_client","Malformed HTTP Basic client authentication.")}}o(V_,"readBasicClientSecret");function F_(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new L("invalid_request","Authenticated client_id must match request client_id.");let t=e.basicClientId??e.bodyClientId;if(t===void 0)throw new L("invalid_client","Client authentication or client_id is required.");return t}o(F_,"resolveAuthenticatedClientId");function Z_(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new L("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");async function K_(e){let t=Ne.parse(e.clientId);return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await le(e.clientSecret)}}o(K_,"buildRuntimeHttpClientAuth");async function J_(e){Tz(e.body);let t=kz.parse(e.body),r=V_(e.authorizationHeader),n=F_({basicClientId:r.clientId,bodyClientId:t.client_id}),a=new Date,i=Z_({basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret});return Oz({parsed:t,clientId:n,clientSecretInput:i,now:a,requestUrl:e.requestUrl,context:e.context})}o(J_,"exchangeDownstreamToken");async function Oz(e){let t=await K_({clientId:e.clientId,...e.clientSecretInput});if(e.parsed.grant_type==="authorization_code"){za(e.parsed.redirect_uri),Ma(e.parsed.scope),e.parsed.resource!==void 0&&co(e.requestUrl??e.parsed.resource,e.parsed.resource);let c=jt(),d=jt(),p=re(Dt(e.now,Ez())),l=Uz(e.now,p),m=await K().exchangeAuthorizationCode({clientAuth:t,codeHash:await le(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await If(e.parsed.code_verifier),currentRefreshTokenHash:await le(c),accessTokenHash:await le(d),grantExpiresAt:p,accessTokenExpiresAt:l.expiresAt,now:re(e.now)});if(m.kind==="invalid_client")throw new L("invalid_client","Client authentication failed.");if(m.kind==="resource_mismatch")throw new L("invalid_target","Token request resource must match the authorization code resource.");if(m.kind!=="exchanged")throw new L("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&V(e.context,{eventType:B.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"authorization_code"}}),{access_token:d,token_type:"Bearer",expires_in:l.expiresIn,refresh_token:c,scope:m.grant.scope,resource:m.grant.resource}}Ma(e.parsed.scope),e.parsed.resource!==void 0&&co(e.requestUrl??e.parsed.resource,e.parsed.resource);let r=jt(),n=jt(),a=re(Dt(e.now,G_())),i=await K().refreshToken({clientAuth:t,currentRefreshTokenHash:await le(e.parsed.refresh_token),nextRefreshTokenHash:await le(r),accessTokenHash:await le(n),...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},accessTokenExpiresAt:a,now:re(e.now)});if(i.kind==="invalid_client")throw new L("invalid_client","Client authentication failed.");if(i.kind==="resource_mismatch")throw new L("invalid_target","Token request resource must match the refresh token grant resource.");if(i.kind!=="rotated")throw new L("invalid_grant","Refresh token is invalid, expired, or revoked.");co(e.requestUrl??i.grant.resource,i.grant.resource);let s=i.accessToken.expiresAt;return e.context&&(V(e.context,{eventType:B.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),V(e.context,{eventType:B.MCP_OAUTH_TOKEN_REFRESH_ROTATED,outcome:"success",attributes:{clientId:e.clientId}})),{access_token:n,token_type:"Bearer",expires_in:Math.max(1,Math.floor((new Date(s).getTime()-e.now.getTime())/1e3)),refresh_token:r,scope:i.grant.scope,resource:i.grant.resource}}o(Oz,"exchangeDownstreamTokenWithRuntimeHttp");async function W_(e){let t=Az.parse(e.body),r=V_(e.authorizationHeader),n=F_({basicClientId:r.clientId,bodyClientId:t.client_id}),a=Z_({basicClientSecret:r.clientSecret,bodyClientSecret:t.client_secret}),i=new Date;if((await K().revokeOAuthToken({clientAuth:await K_({clientId:n,...a}),tokenHash:await le(t.token),now:re(i)})).kind==="invalid_client")throw new L("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&&V(e.context,{eventType:B.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}o(W_,"revokeDownstreamToken");var $z=64*1024,zz=16*1024,Mz="text/html; charset=utf-8";function qz(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(qz,"formDataToObject");async function Nz(e){return Zv(e,{maxBytes:$z,label:"Request body"})}o(Nz,"readJsonBody");async function Ks(e){return qz(await Hs(e,{maxBytes:zz,label:"Request body"}))}o(Ks,"readFormBody");async function Js(e,t,r){let n=ge(r),a=r instanceof u.ZodError?Y_(r):void 0,i={code:n??(r instanceof u.ZodError?"invalid_request":"internal_server_error")};return a!==void 0&&(i.detail=a),it(e,t,i)}o(Js,"handleProblem");function qa(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(qa,"oauthErrorResponse");function Dz(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(Dz,"readOAuthProtocolHeaders");function jz(e,t){let r=Ke("internal_server_error");return qa({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:Dz(e,t)})}o(jz,"oauthProtocolErrorResponse");function Hz(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(Hz,"readZodOAuthErrorCode");function Lz(e){let t={error:Hz(e)},r=Y_(e);return r!==void 0&&(t.errorDescription=r),qa(t)}o(Lz,"oauthZodErrorResponse");function Bz(e){let t=ge(e);if(t===void 0)return;let r=Ke(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:Vz(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,qa(n)}o(Bz,"oauthGatewayProblemResponse");function Gz(){let t={error:"server_error",status:500,errorDescription:Ke("internal_server_error").publicDetail};return qa(t)}o(Gz,"oauthFallbackErrorResponse");function Vz(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(Vz,"readOAuthStatus");function uo(e,t={}){return e instanceof fn?Fz(e):e instanceof L?jz(e,t):e instanceof u.ZodError?Lz(e):Bz(e)??Gz()}o(uo,"oauthProblemResponse");function zt(e,t,r){let n={event:t},a=!1;if(r instanceof L)n.oauthError=r.errorCode,n.status=r.status,Ye(n,"error",r);else if(r instanceof fn)n.oauthError=r.errorCode,Ye(n,"error",r);else if(r instanceof u.ZodError){n.code="invalid_request",Ye(n,"error",r);let i=r.issues[0];i&&(n.zodPath=i.path.join("."))}else{let i=ge(r);if(i!==void 0){let s=Ke(i);n.code=i,n.status=s.status,s.oauthError!==void 0&&(n.oauthError=s.oauthError),a=s.status>=500||s.oauthError==="server_error",Ye(n,"error",r)}else a=!0,Ye(n,"error",r)}if(a){let i=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(n,i.message)}else e.log.warn(n,"OAuth handler rejected the request")}o(zt,"logUnexpectedOAuthHandlerError");function Fz(e){let t;try{t=new URL(e.redirectUri)}catch{return qa({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(Fz,"downstreamAuthorizeRedirectErrorResponse");function Y_(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(Y_,"formatZodErrorDetail");function Zz(e,t){let r={event:"browser_login_callback_failed",code:ge(t)??"invalid_request"};Ye(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(Zz,"logBrowserLoginCallbackFailure");function Op(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(Op,"redirectResultResponse");function Ws(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":Mz,"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 Op(e)}o(Ws,"authorizeResultResponse");async function Q_(e,t){try{return Response.json(xc(e.url))}catch(r){return zt(t,"oauth_authorization_server_metadata_failed",r),Js(e,t,r)}}o(Q_,"authorizationServerMetadataHandler");async function X_(e,t){try{let r=xe.parse(e.params.virtualServerId),n=Mr(r);return Response.json(wm({virtualServerId:n.virtualServerId,requestUrl:e.url}))}catch(r){return zt(t,"oauth_authorization_server_metadata_failed",r),Js(e,t,r)}}o(X_,"scopedAuthorizationServerMetadataHandler");async function ew(e,t){try{let r=await O_(await Nz(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"),V(t,{eventType:B.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 zt(t,"oauth_register_failed",r),uo(r)}}o(ew,"registerHandler");async function tw(e,t){try{return Ws(await Up(e,{context:t}))}catch(r){return zt(t,"oauth_authorize_failed",r),uo(r,{includeInvalidClientChallenge:!1})}}o(tw,"authorizeHandler");async function rw(e,t){try{let r=xe.parse(e.params.virtualServerId),n=Mr(r);return Ws(await Up(e,{virtualServerId:n.virtualServerId,context:t}))}catch(r){return zt(t,"oauth_authorize_scoped_failed",r),uo(r,{includeInvalidClientChallenge:!1})}}o(rw,"scopedAuthorizeHandler");async function nw(e,t){try{let r=await j_(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),Ws(r)}catch(r){return Zz(t,r),Js(e,t,r)}}o(nw,"callbackHandler");async function ow(e,t){try{return Op(await H_(e))}catch(r){return zt(t,"oauth_dev_login_failed",r),uo(r)}}o(ow,"devLoginHandler");async function aw(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?t_(r,n):yp(r,400)}return e.method!=="POST"?new Response(null,{status:405,headers:{allow:"GET, POST"}}):Op(await L_({request:e,body:await Ks(e)}))}catch(n){return zt(t,"oauth_api_key_login_failed",n),yp(r)}}o(aw,"apiKeyLoginHandler");async function iw(e,t){try{if(!["GET","POST"].includes(e.method))return new Response(null,{status:405,headers:{allow:"GET, POST"}});let r=await B_({request:e,body:e.method==="POST"?await Ks(e):void 0,context:t});return Ws(r)}catch(r){return zt(t,"oauth_setup_failed",r),Js(e,t,r)}}o(iw,"setupHandler");async function sw(e,t){try{return Response.json(await J_({body:await Ks(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return zt(t,"oauth_token_failed",r),uo(r)}}o(sw,"tokenHandler");async function cw(e,t){try{return await W_({body:await Ks(e),authorizationHeader:e.headers.get("authorization"),context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return zt(t,"oauth_revoke_failed",r),uo(r)}}o(cw,"revokeHandler");var Kz={connect:"Connect",app_password:"App password",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},uw=new Ct("upstream-request");function Jz(e){let t=uw.get(e);if(!t)throw g("internal_server_error","Upstream request context has not been set");return t}o(Jz,"readUpstreamRequestContext");function Wz(e,t){return t.some(r=>r===e)}o(Wz,"requestContextMatchesKind");function Yz(e){return typeof e=="string"?[e]:e}o(Yz,"toExpectedKinds");function hn(e,t){uw.set(e,t)}o(hn,"setUpstreamRequestContext");function gn(e,t){let r=Jz(e),n=Yz(t);if(!Wz(r.kind,n)){let a=Kz[n[0]];throw g("internal_server_error",`${a} request context has not been set`)}return r}o(gn,"requireUpstreamRequestContext");function dw(e){return ce`<form class="form" method="post" action="${e.action}" autocomplete="off"><input type="hidden" name="browserTicket" value="${e.browserTicket}" />${e.fields}<p class="form__note">The gateway stores this encrypted and keeps it out of MCP client
|
|
62
|
-
configuration.</p><button class="button button--primary button--block form__submit" type="submit" >Connect</button></form>`}o(
|
|
63
|
-
`).slice(1,4).map(t=>t.trim()).join(" | ")}o(SM,"readFirstStackFrame");function hw(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=SM(r))}o(hw,"addErrorAttributes");function gw(e){try{return new URL(e).host}catch{return""}}o(gw,"safeHostFromUrl");function vM(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"),V(e,{eventType:B.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:t.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:t.error,errorDescription:t.errorDescription}}),lo(r,"provider_access_denied");case"callback_invalid":return e.log.warn({event:"upstream_oauth_callback_invalid",code:"oauth_state_invalid",upstreamServerId:t.upstreamServerId},"Upstream OAuth callback request missing required code/state parameters"),lo(r,"oauth_state_invalid");case"callback_authorization_code":return t}}o(vM,"requireAuthorizationCallbackRequest");function _M(e,t){V(e,{eventType:B.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(_M,"emitCallbackReceivedAnalyticsEvent");function wM(e,t){V(e,{eventType:B.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.virtualServerId})}o(wM,"emitTokenExchangeSucceededAnalyticsEvent");function bM(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return Ys({host:gw(e.url),title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}o(bM,"buildSuccessfulCallbackResponse");function RM(e){let t={detail:e instanceof Error?e.message:void 0};return hw(t,"error",e),e instanceof Error&&hw(t,"cause",yM(e)),t}o(RM,"buildTokenExchangeFailureAttributes");function CM(e){V(e.context,{eventType:B.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:ge(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:RM(e.error)})}o(CM,"emitTokenExchangeFailedAnalyticsEvent");function IM(e,t){let r=ge(t);return lo(e,Va(r)?r:"upstream_token_exchange_failed")}o(IM,"tokenExchangeFailureResponse");async function Mp(e,t){let r=gn(t,gM),n=gw(e.url),a=vM(t,r,n);if(a instanceof Response)return a;_M(t,a);try{let i=await hg({request:e,callbackRequest:a});return wM(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"),bM(e,i)}catch(i){let s={event:"upstream_oauth_token_exchange_failed",code:ge(i)??"upstream_token_exchange_failed",upstreamServerId:a.upstreamServerId};return Ye(s,"error",i),t.log.warn(s,"Upstream OAuth token exchange failed; user shown connection-failure page"),CM({context:t,callbackRequest:a,error:i}),IM(n,i)}}o(Mp,"callbackHandler");function PM(e){let t=ge(e);return t==="unknown_upstream_server"?t:"not_found"}o(PM,"clientMetadataProblemCode");function xM(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(xM,"clientMetadataProblemDetail");async function yw(e,t){let r=gn(t,"connect"),n=await fg({request:e,connectRequest:r});if(V(t,{eventType:B.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 qn({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(yw,"connectHandler");async function Sw(e,t){let r=gn(t,"client_metadata");try{let n=eg(e.url),a=tg(n,r.upstreamServerId,r.authProfileId);return Response.json(a)}catch(n){let a=PM(n),i=n instanceof Error?n.message:String(n);return t.log.warn({event:"oauth_client_metadata_request_failed",code:a,upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:i},"Failed to serve OAuth client metadata document for upstream connection"),it(e,t,{code:a,detail:xM(n)})}}o(Sw,"oauthClientMetadataHandler");function nr(e){if(typeof e=="string"&&e.length!==0)return e}o(nr,"readOptionalQueryString");function kM(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw g("internal_server_error",`Validated path parameter ${t} is missing`);return r}o(kM,"requirePathString");function vw(e){let t=nr(e);return t?xe.parse(t):void 0}o(vw,"readOptionalVirtualServerId");function TM(e,t){let r=nr(e);return r?We.parse(r):$n(t,"user-oauth")}o(TM,"readOptionalAuthProfileId");function AM(e){let t=vw(e);if(!t)throw g("invalid_request","virtualServerId query parameter is required.");return t}o(AM,"readRequiredVirtualServerId");function EM(e){let t=nr(e.query.browserTicket);return t===void 0?{}:{browserTicket:t}}o(EM,"readOptionalBrowserTicket");function UM(e){let t=ri(nr(e));return t===void 0?{}:{returnTo:t}}o(UM,"readOptionalReturnTo");function OM(e){let t=vw(e.query.virtualServerId);return t===void 0?{}:{virtualServerId:t}}o(OM,"readOptionalVirtualServerIdContext");function $M(e){let t=nr(e.query.error_description);return t===void 0?{}:{errorDescription:t}}o($M,"readOptionalProviderErrorDescription");function zM(e){let t=Pt(e.authMode);if(t.connectSupport!=="none")return e;throw g("invalid_request",t.connectUnsupportedDetail??"This upstream does not support browser connection flows.")}o(zM,"requireConnectableRouteAuth");function MM(e,t,r,n){let a=js(e,t);if(a.ownerMode==="none"||a.authMode==="shared-secret")throw g("invalid_request","Static-secret upstreams do not support browser connection flows.");return{kind:"connect",...a,...n===void 0?{}:{returnTo:n},redirect:r}}o(MM,"buildConnectContextForPrincipal");function qM(e,t,r){let n=Pn(t),a=Pt(e.authMode);if(n.mode!==a.ownerMode)throw g("oauth_callback_mismatch","Browser connect ticket did not match the requested upstream flow");return{kind:"connect",...e,...t.returnTo===void 0?{}:{returnTo:t.returnTo},owner:n,initiatedBySubjectId:t.initiatedBySubjectId,redirect:r}}o(qM,"buildConnectContextForTicket");async function NM(e,t){let r=zM(Gv(t,AM(e.query.virtualServerId))),n=e.query.redirect==="true",a=nr(e.query.browserTicket);if(e.user){if(a)throw g("invalid_request","Use either an authenticated gateway request or a browser connect ticket, not both.");let s=Rn(e.user,e.url);return MM(r,s,n,UM(e.query.returnTo).returnTo)}if(!a)throw g("authentication_required","Authentication is required to start the upstream connection flow.");let i=await Oi(a);if(i.ownerMode!==r.ownerMode||i.upstreamServerId!==r.upstreamServerId||i.authProfileId!==r.authProfileId||i.virtualServerId!==r.virtualServerId)throw g("oauth_callback_mismatch","Browser connect ticket did not match the requested upstream flow");return await $i(i),qM(r,i,n)}o(NM,"resolveConnectContext");async function DM(e,t,r){let n=Je.parse(kM(e,"connection"));switch(r){case"connect":hn(t,await NM(e,n));return;case"app_password":hn(t,{kind:"app_password",upstreamServerId:n,...OM(e),...EM(e)});return;case"callback":{let a=nr(e.query.error);if(a){hn(t,{kind:"callback_provider_error",upstreamServerId:n,error:a,...$M(e)});return}let i=nr(e.query.code),s=nr(e.query.state);if(i&&s){hn(t,{kind:"callback_authorization_code",upstreamServerId:n,code:i,state:s});return}hn(t,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":hn(t,{kind:"client_metadata",upstreamServerId:n,authProfileId:TM(e.query.authProfileId,n)});return}}o(DM,"resolveUpstreamRequestInbound");async function jM(e,t,r){try{await DM(e,t,r);return}catch(n){let a=ge(n);if(!a)throw n;let i=n instanceof Error?n.message:void 0;return it(e,t,{code:a,...i===void 0?{}:{detail:i}})}}o(jM,"applyUpstreamRequestContext");function Na(e,t){return o(async(n,a)=>{let i=await jM(n,a,e);return i||t(n,a)},"wrapped")}o(Na,"withUpstreamRequestContext");var HM={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function LM(){return new Response(null,{status:204,headers:HM})}o(LM,"buildWellKnownPreflightResponse");function BM(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(BM,"withWellKnownCorsHeaders");function qp(e){return async(t,r)=>t.method==="OPTIONS"?LM():BM(await e(t,r))}o(qp,"wrapWellKnownHandler");var GM=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:qp(Q_),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:qp(X_),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:qp(bm),corsPolicy:"anything-goes"},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:ew},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:tw},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/mcp/:virtualServerId",methods:["GET"],handler:rw},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:nw},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:ow},{routeName:"oauth_api_key_login",path:"/oauth/api-key-login",methods:["GET","POST"],handler:aw},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:iw},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:sw},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:cw},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:Na("client_metadata",Sw)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:Na("connect",yw)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:Na("callback",Mp)},{routeName:"upstream_app_password",path:"/auth/connections/:connection/app-password",methods:["GET","POST"],handler:Na("app_password",zp)}];function _w(e){return e?.some(t=>ko(t.policyType))??!1}o(_w,"shouldRegisterMcpGatewayInternalRoutes");function VM(e){let t=Af(e.policies);if(!t){let r=[...Wc].map(n=>`\`${n}\``).join(", ");throw new ue(`MCP gateway: could not find an MCP authorization policy in policies.json. Add one of [${r}] and reference it on your MCP routes.`)}return nh(zu({routes:e.routes,policies:e.policies})),t.config}o(VM,"initializeMcpGatewayState");function FM(e,t,r){return async(n,a)=>{let i=a;bn(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(FM,"wrapInternalHandler");function ww(e,t){let r,n=o(()=>(r===void 0&&(r=VM(t)),r),"readOAuthConfig");for(let a of GM){let i=FM(a.routeName,a.handler,n),s=o((c,d)=>i(c,d),"handler");e.addPluginRoute({path:a.path,methods:a.methods,handler:s,processors:[ic],corsPolicy:a.corsPolicy??"none"})}}o(ww,"registerMcpGatewayInternalRoutes");function bw(e){rh(e)}o(bw,"configureLazyMcpGatewayState");var Np=class extends Kp{static{o(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;if(!r||!_w(r.policies))return;let n={routes:r.routes,policies:r.policies};bw(n),ww(t.router,n)}};export{Zc as McpAuth0OAuthInboundPolicy,Np as McpGatewayPlugin,Kc as McpOAuthInboundPolicy,hp as McpUpstreamConnectionInboundPolicy,WO as McpVirtualServerHandler,Px 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(ar,"renderShell");var yp="zuplo.com";function s_(e){return`https://www.google.com/s2/favicons?domain=${e}&sz=128`}o(s_,"s2FaviconHref");function f$(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(f$,"strictFaviconHref");var fn=s_(yp);function hn(e){let t=e.toLowerCase();return t===yp||t==="zuplo.app"||t==="zuplo.dev"||t.endsWith(".zuplo.app")||t.endsWith(".zuplo.dev")?s_(yp):f$(e)}o(hn,"resolveIconHref");function gn(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(gn,"renderShellIcon");function c_(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(c_,"renderActions");var p3=nr('<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 u_(){return se`<p>The API key could not be verified. Start the authorization flow again to try
|
|
59
|
+
once more.</p>`}o(u_,"renderApiKeyLoginFailure");function d_(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(d_,"renderApiKeyLoginForm");var m3=nr('<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>'),f3=nr('<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 h3=nr('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M7.13 2.46 1.39 12.5a1 1 0 0 0 .87 1.5h11.48a1 1 0 0 0 .87-1.5L8.87 2.46a1 1 0 0 0-1.74 0Z"/><line x1="8" y1="6" x2="8" y2="9.4"/><circle cx="8" cy="11.4" r=".7" fill="currentColor" stroke="none"/></svg>');var h$="text/html; charset=utf-8";function l_(e,t=200){return new Response(Mr(e),{status:t,headers:{"content-type":h$,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(l_,"apiKeyLoginHtmlResponse");function Sp(e,t=401){let r=hn(e);return l_(ar({title:"Sign-in failed",iconHref:r,styles:or,headerIcon:gn({iconHref:r,fallbackIconHref:fn}),heading:"Sign-in failed",subhead:"",body:u_(),footer:""}),t)}o(Sp,"apiKeyLoginFailureResponse");function p_(e,t){let r=hn(e);return l_(ar({title:"Sign in",iconHref:r,styles:or,headerIcon:gn({iconHref:r,fallbackIconHref:fn}),heading:"Sign in",subhead:se`<p class="card__subtitle">Enter your API key to continue.</p>`,body:d_({state:t}),footer:""}))}o(p_,"renderApiKeyLoginForm");ue();ue();import{errors as __,jwtVerify as w_,SignJWT as b_}from"jose";ue();import{errors as x$,jwtVerify as k$,SignJWT as T$}from"jose";function zr(e){let t=ke().browserLogin[e];if(typeof t=="string"&&t.length>0)return t;throw g("internal_server_error",`browserLogin.${e} is required for federated browser login. Set it on the mcp-oauth-inbound policy options.`)}o(zr,"requireBrowserLoginField");ue();import{createRemoteJWKSet as y$,errors as za,jwtVerify as S$}from"jose";var v$=u.object({id_token:u.string().min(1),token_type:u.string().min(1).optional(),expires_in:u.number().optional(),access_token:u.string().min(1).optional(),refresh_token:u.string().min(1).optional(),scope:u.string().min(1).optional()}),_$=u.object({error:u.string().min(1).optional(),error_description:u.string().min(1).optional(),error_uri:u.string().min(1).optional()});function w$(e){let t=_$.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(w$,"readIdpErrorFields");function b$(e){return e instanceof za.JWTExpired?"expired":e instanceof za.JWTClaimValidationFailed?"claim":e instanceof za.JWSSignatureVerificationFailed?"signature":e instanceof za.JWKSNoMatchingKey?"jwks_no_match":e instanceof za.JWTInvalid?"invalid":e instanceof u.ZodError?"schema":"other"}o(b$,"readJwtFailureKind");var R$=u.object({sub:ve,nonce:u.string().min(1)}).catchall(u.unknown()),vp;function C$(e){return e instanceof Error&&"cause"in e?e.cause:e}o(C$,"readErrorCause");function I$(e){if(e!==null&&typeof e=="object"&&"extensionMembers"in e)return e.extensionMembers?.gatewayCode}o(I$,"readRuntimeGatewayCode");function P$(){if(!vp){let e=ke();vp=y$(new URL(e.oidc.jwksUrl),{timeoutDuration:e.browserLogin.remoteTimeoutMs})}return vp}o(P$,"readFederatedJwks");async function m_(e){let t=ke(),r=zr("tokenUrl"),n=zr("clientId"),a=zr("clientSecret"),i=new URL("/oauth/callback",vt(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 wh(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=w$(d);throw e.context?.log.warn({event:"federated_token_exchange_failed",code:"provider_access_denied",idpHost:lt(r),idpStatus:c.status,...h},"Federated browser login token exchange returned non-2xx from the identity provider"),g({code:"provider_access_denied",privateDetail:"Federated browser login token exchange failed.",cause:new Error(`IdP token exchange failed (status=${c.status}${h.idpError?` idp_error=${h.idpError}`:""}${h.idpErrorDescription?` idp_error_description=${h.idpErrorDescription}`:""})`)})}let p=v$.parse(d),l;try{({payload:l}=await S$(p.id_token,P$(),{issuer:t.oidc.issuer,audience:n}))}catch(h){let y={};throw Ye(y,"error",h),e.context?.log.warn({event:"federated_id_token_verification_failed",code:"browser_login_verification_failed",failureKind:b$(h),idpHost:lt(r),expectedIssuer:t.oidc.issuer,...y},"Federated id_token failed jose verification"),h}if(l.nonce!==e.nonce)throw e.context?.log.warn({event:"federated_nonce_mismatch",code:"oauth_callback_mismatch",idpHost:lt(r),nonceMissingFromIdToken:l.nonce===void 0},"Federated id_token nonce did not match the signed gateway state"),g("oauth_callback_mismatch","Federated browser login nonce did not match the signed gateway state.");let m=R$.parse(l);return xn({sub:m.sub,data:m},e.requestUrl)}catch(c){let d=ge(c)??I$(c);throw d!==void 0&&d!=="browser_login_verification_failed"?c:g("browser_login_verification_failed","Federated browser login callback could not be verified.",C$(c))}}o(m_,"exchangeFederatedAuthorizationCode");var wp="zuplo_mcp_session",A$=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 E$(e){let t=new Map;if(!e)return t;for(let r of e.split(";")){let n=r.indexOf("=");if(n<0)continue;let a=r.slice(0,n).trim(),i=r.slice(n+1).trim();if(a)try{t.set(a,decodeURIComponent(i))}catch{t.set(a,i)}}return t}o(E$,"parseCookieHeader");async function f_(){return Et({purpose:"browser-session",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Sr(e,"browser-session"),"derive")})}o(f_,"getBrowserSessionKey");function _p(e){let t=new URL(ae(e)),r=[`${wp}=`,"Path=/","HttpOnly","SameSite=Lax","Max-Age=0"];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(_p,"buildBrowserSessionEvictionCookie");function U$(e){let t=new URL(ae(e.requestUrl)),r=[`${wp}=${encodeURIComponent(e.value)}`,"Path=/","HttpOnly","SameSite=Lax",`Max-Age=${e.ttlSeconds}`];return t.protocol==="https:"&&r.push("Secure"),r.join("; ")}o(U$,"serializeSessionCookie");function h_(e={}){return new URL(zr("url")).origin}o(h_,"readBrowserLoginOrigin");function bp(){return ke().browserLogin.stateTtlSeconds}o(bp,"readBrowserLoginStateTtlSeconds");function g_(e){if(!e.user)throw g("authentication_required","The browser login callback did not include an authenticated Zuplo principal.");return xn(e.user,e.url)}o(g_,"resolveCurrentRequestPrincipal");async function Vs(e,t={}){let r=E$(e.headers.get("cookie")).get(wp);if(!r)return{};try{let{payload:n}=await k$(r,await f_(),{algorithms:[st],issuer:Qe,audience:it}),a=A$.parse(n);if(a.browserLoginOrigin!==h_(t))return{evictCookie:_p(e.url)};let i={subjectId:a.sub};return a.roles&&a.roles.length>0&&(i.roles=a.roles),{principal:i}}catch(n){return n instanceof x$.JWTExpired?{evictCookie:_p(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:_p(e.url)})}}o(Vs,"readBrowserSession");async function qa(e){let t=ke().browserLogin.sessionTtlSeconds,r={purpose:"gateway_browser_session",sub:e.principal.subjectId,browserLoginOrigin:h_({virtualServerId:e.virtualServerId})};e.principal.roles&&(r.roles=e.principal.roles);let n=await new T$(r).setProtectedHeader({alg:st,typ:"JWT"}).setIssuer(Qe).setAudience(it).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+t).sign(await f_());return U$({value:n,requestUrl:e.requestUrl,ttlSeconds:t})}o(qa,"createBrowserSessionCookie");async function y_(e){throw g("forbidden","API-key browser login is not supported in this gateway.")}o(y_,"resolveApiKeyBrowserLoginPrincipal");async function S_(e){let t={};e.context!==void 0&&(t.context=e.context);let r=await Vs(e.request,t);if(r.principal)return r.principal;let n=typeof e.request.query.code=="string"?e.request.query.code:void 0;if(!n)throw g("oauth_callback_mismatch","Federated browser login callback is missing an authorization code.");return m_({code:n,nonce:e.stateId,requestUrl:e.request.url,...e.context===void 0?{}:{context:e.context}})}o(S_,"resolveBrowserLoginCallbackPrincipal");function v_(e){let t=ke().browserLogin,r=new URL(zr("url")),n=new URL("/oauth/callback",vt(e.requestUrl));return Im(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",zr("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(v_,"buildBrowserLoginUrl");var O$={invalid_request:400,invalid_client:401,invalid_grant:400,invalid_target:400,unsupported_grant_type:400,server_error:500,invalid_redirect_uri:400,invalid_client_metadata:400},M=class extends Error{static{o(this,"OAuthProtocolError")}errorCode;status;constructor(t,r,n=O$[t],a){super(r,a),this.name="OAuthProtocolError",this.errorCode=t,this.status=n}};var $$=5*60,M$=u.object({purpose:u.literal("gateway_browser_login"),transactionId:pt,stateId:ri,exp:u.number().int().positive(),iat:u.number().int().positive().optional()}),z$=u.object({purpose:u.literal("gateway_authorization_setup"),transactionId:pt,stateId:ri,exp:u.number().int().positive(),iat:u.number().int().positive().optional()});async function R_(){return Et({purpose:"browser-login",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Sr(e,"browser-login"),"derive")})}o(R_,"getBrowserLoginKey");async function C_(){return Et({purpose:"authorization-csrf",keyMaterialPurpose:"oauth-state-signing",derive:o(e=>Sr(e,"authorization-csrf"),"derive")})}o(C_,"getCsrfKey");function I_(e){return{now:e.now??new Date,ttlSeconds:bp()}}o(I_,"readPendingTransactionDependencies");function q$(e,t){return e.subjectId===t.subjectId}o(q$,"principalsMatch");function P_(e){return{subjectId:e.subjectId,...e.roles===void 0?{}:{roles:e.roles}}}o(P_,"toPendingPrincipal");function x_(e){let t={id:e.id,currentStateHash:e.currentStateHash,clientId:e.transaction.clientId,redirectUri:e.transaction.redirectUri,resource:e.transaction.resource,virtualServerId:e.transaction.virtualServerId,scope:e.transaction.scope,codeChallenge:e.transaction.codeChallenge,codeChallengeMethod:e.transaction.codeChallengeMethod,createdAt:re(e.now),expiresAt:re(Bt(e.now,e.ttlSeconds)),...e.transaction.clientState===void 0?{}:{clientState:e.transaction.clientState}};if(e.phase==="awaiting_login")return{...t,phase:"awaiting_login"};if(!e.principal)throw g("identity_context_missing","Authorization setup requires a principal.");return{...t,phase:"awaiting_setup",principal:P_(e.principal)}}o(x_,"createTransactionRecord");async function k_(e){let{id:t,...r}=e.record,n=await K().startAuthorization({...r,transactionId:t,...e.client===void 0?{}:{client:e.client}});switch(n.kind){case"started":return n.transaction;case"already_exists":throw g("oauth_state_reused","Authorization transaction state already exists.");case"invalid_client":throw new M("invalid_client","OAuth client is not registered.");case"redirect_uri_mismatch":throw new M("invalid_request","redirect_uri is not registered for the client.")}}o(k_,"startPendingTransaction");async function N$(e){return new b_({purpose:"gateway_browser_login",transactionId:e.transactionId,stateId:e.stateId}).setProtectedHeader({alg:st,typ:"JWT"}).setIssuer(Qe).setAudience(it).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await R_())}o(N$,"signBrowserLoginState");async function T_(e){return new b_({purpose:"gateway_authorization_setup",transactionId:e.transactionId,stateId:Ic()}).setProtectedHeader({alg:st,typ:"JWT"}).setIssuer(Qe).setAudience(it).setIssuedAt().setExpirationTime(Math.floor(Date.now()/1e3)+e.ttlSeconds).sign(await C_())}o(T_,"signCsrfToken");async function Fs(e){try{let{payload:t}=await w_(e,await R_(),{algorithms:[st],issuer:Qe,audience:it}),r=M$.parse(t);return{transactionId:r.transactionId,stateId:r.stateId}}catch(t){throw t instanceof __.JWTExpired?g("oauth_state_expired","Browser login state has expired.",t):g("oauth_state_invalid","Browser login state could not be verified.",t)}}o(Fs,"verifyBrowserLoginStateToken");async function Rp(e){try{let{payload:t}=await w_(e,await C_(),{algorithms:[st],issuer:Qe,audience:it});return{transactionId:z$.parse(t).transactionId}}catch(t){throw t instanceof __.JWTExpired?g("oauth_state_expired","Authorization setup state has expired.",t):g("oauth_state_invalid","Authorization setup state could not be verified.",t)}}o(Rp,"verifyCsrfToken");function Zs(e){return e==="consumed"||e==="consumed_already"||e==="stale_hash"?"oauth_state_reused":e==="expired"?"oauth_state_expired":"oauth_state_invalid"}o(Zs,"pendingStateErrorCode");function A_(e){return e.kind==="available"?{kind:"available",record:e.transaction}:e}o(A_,"toPendingAuthorizationGetResult");function j$(e){return e.kind==="advanced"?{kind:"advanced",record:e.transaction}:e}o(j$,"toPendingAuthorizationAdvanceResult");function E_(e){return e==="principal_mismatch"?"oauth_callback_mismatch":Zs(e==="consumed_already"?"consumed_already":e)}o(E_,"setupDecisionErrorCode");function D$(e){if(e.kind!=="available")throw g(Zs(e.kind),"Authorization setup state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization setup state is not in the setup phase.");return e.record}o(D$,"requireAwaitingSetup");function H$(e){if(e.kind!=="available")throw g(Zs(e.kind),"Browser login state is invalid, expired, or already used.");if(e.record.phase!=="awaiting_login")throw g("oauth_state_invalid","Browser login state is not in the login phase.");return e.record}o(H$,"requireAwaitingLogin");function L$(e){if(!q$(e.currentBrowserPrincipal,e.transaction.principal))throw g("oauth_callback_mismatch","Authorization setup state does not match the current browser session.")}o(L$,"requireCurrentPrincipalMatches");async function U_(e){let t=e.now??new Date,r=bp(),n=Cc(),a=Ic(),i=await N$({transactionId:n,stateId:a,ttlSeconds:r}),s=x_({id:n,transaction:e.transaction,currentStateHash:await le(i),phase:"awaiting_login",now:t,ttlSeconds:r});if(s.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");let c=await k_({record:s,client:e.transaction.client});if(c.phase!=="awaiting_login")throw g("oauth_state_invalid","Authorization transaction did not start in login phase.");return{transaction:c,browserLoginStateToken:i,browserLoginUrl:v_({state:i,nonce:a,virtualServerId:s.virtualServerId,requestUrl:e.requestUrl})}}o(U_,"startAwaitingLogin");async function O_(e){let{now:t,ttlSeconds:r}=I_(e),n=Cc(),a=await T_({transactionId:n,ttlSeconds:r}),i=x_({id:n,transaction:e.transaction,currentStateHash:await le(a),phase:"awaiting_setup",principal:e.principal,now:t,ttlSeconds:r});if(i.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");let s=await k_({record:i,client:e.transaction.client});if(s.phase!=="awaiting_setup")throw g("oauth_state_invalid","Authorization transaction did not start in setup phase.");return{transaction:s,csrfToken:a}}o(O_,"startAwaitingSetup");async function Cp(e){let{now:t,ttlSeconds:r}=I_(e),n=await Fs(e.browserLoginStateToken),a=await T_({transactionId:n.transactionId,ttlSeconds:r}),i=j$(await K().advancePendingAuthorization({transactionId:n.transactionId,expectedPhase:"awaiting_login",currentStateHash:await le(e.browserLoginStateToken),nextStateHash:await le(a),nextPhase:"awaiting_setup",principal:P_(e.principal),now:re(t)}));if(i.kind!=="advanced")throw g(Zs(i.kind),"Browser login state is invalid, expired, or already used.");if(i.record.phase!=="awaiting_setup")throw g("oauth_state_invalid","Browser login did not advance to setup.");return{transaction:i.record,csrfToken:a}}o(Cp,"completeLogin");async function $_(e){let t=e.now??new Date,r=await Fs(e.browserLoginStateToken);return H$(A_(await K().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await le(e.browserLoginStateToken),now:re(t)})))}o($_,"getAwaitingLogin");async function M_(e){let t=await Ip(e);return L$({transaction:t,currentBrowserPrincipal:e.currentBrowserPrincipal}),t}o(M_,"getSetup");async function Ip(e){let t=e.now??new Date,r=await Rp(e.csrfToken);return D$(A_(await K().readPendingAuthorization({transactionId:r.transactionId,currentStateHash:await le(e.csrfToken),now:re(t)})))}o(Ip,"getSetupTransaction");async function B$(e){let t=await Rp(e.csrfToken),r=Gt(),n=re(Bt(e.now,$$)),a=await K().decideAuthorizationSetup({decision:"approve",transactionId:t.transactionId,currentStateHash:await le(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},authorizationCodeHash:await le(r),authorizationCodeExpiresAt:n,grantId:Rm(),now:re(e.now)});if(a.kind!=="approved")throw g(a.kind==="cancelled"?"oauth_state_invalid":E_(a.kind),"Authorization setup state is invalid, expired, or already used.");let i=new URL(a.transaction.redirectUri);return i.searchParams.set("code",r),a.transaction.clientState&&i.searchParams.set("state",a.transaction.clientState),i}o(B$,"createAuthorizationCodeRedirectWithDecision");async function G$(e){let t=await Rp(e.csrfToken),r=await K().decideAuthorizationSetup({decision:"cancel",transactionId:t.transactionId,currentStateHash:await le(e.csrfToken),currentPrincipal:{subjectId:e.currentBrowserPrincipal.subjectId},now:re(e.now)});if(r.kind!=="cancelled")throw g(r.kind==="approved"?"oauth_state_invalid":E_(r.kind),"Authorization setup state is invalid, expired, or already used.");return V$({redirectUri:r.transaction.redirectUri,clientState:r.transaction.clientState})}o(G$,"createCancelRedirectWithDecision");function V$(e){let t=new URL(e.redirectUri);return t.searchParams.set("error","access_denied"),t.searchParams.set("error_description","The user cancelled the MCP authorization request."),e.clientState!==void 0&&t.searchParams.set("state",e.clientState),t}o(V$,"buildClientCancelRedirect");async function z_(e){let t=e.now??new Date;return B$({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(z_,"approve");async function q_(e){let t=e.now??new Date;return G$({csrfToken:e.csrfToken,currentBrowserPrincipal:e.currentBrowserPrincipal,now:t})}o(q_,"cancel");ue();var F$=1e4,Z$=5*1024,K$=2,J$=90*24*60*60,Pp=["authorization_code","refresh_token"],xp=["code"],W$=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(Pp)).min(1).max(2).optional(),response_types:u.array(u.enum(xp)).min(1).max(1).optional(),scope:u.literal(ye).optional(),token_endpoint_auth_method:_m.default("none")});function Y$(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&xe(t))&&t.pathname!=="/"}catch{return!1}}o(Y$,"isCimdClientIdCandidate");function Na(e,t="invalid_request"){if(Q$(e))throw new M(t,"redirect_uris must not include raw whitespace or control characters.");let r;try{r=new URL(e)}catch{throw new M(t,"redirect_uris must be absolute URIs.")}if(r.hash||r.username||r.password)throw new M(t,"redirect_uris must not include credentials or fragments.");if(!(r.protocol==="https:"||xe(r)))throw new M(t,"redirect_uris must use HTTPS except loopback HTTP redirects for local clients.")}o(Na,"assertValidRedirectUri");function Q$(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r<=32||r>=127&&r<=159)return!0}return!1}o(Q$,"hasForbiddenRawRedirectUriCharacter");async function X$(e){let{response:t,json:r}=await bh(e.initialUrl,{headers:{accept:"application/json"}},{maxRedirects:K$,maxResponseBytes:Z$,timeoutMs:F$});if(!t.ok)throw g("invalid_request","CIMD metadata could not be fetched.");let n=bm.parse(r);if(n.client_id!==e.clientId)throw g("invalid_request","Fetched CIMD client_id must exactly match the requested client_id.");return n}o(X$,"fetchCimdMetadata");async function eM(e){let t=Ai(e),r=await X$({clientId:e,initialUrl:t});return{kind:"cimd",clientId:e,metadata:r}}o(eM,"resolveCimdClient");async function Ks(e,t){let r=Ae.parse(e);if(Y$(r)){if(!ke().gateway.cimdEnabled)throw new M("invalid_client","OAuth client is not registered.");try{return await eM(r)}catch{throw new M("invalid_client","OAuth client is not registered.")}}let n=await K().readClient({clientId:r});if(n.kind==="found"){let a=n.client,i={kind:"dcr",clientId:r,metadata:{client_id:a.clientId,client_name:a.clientName,redirect_uris:a.redirectUris,token_endpoint_auth_method:a.tokenEndpointAuthMethod}};return a.hashedClientSecret&&(i.hashedClientSecret=a.hashedClientSecret),i}throw new M("invalid_client",r.startsWith("dcr:")?"Dynamic client is not registered. Re-run client registration before authorization.":"OAuth client is not registered.")}o(Ks,"resolveClient");function N_(e,t){if(!e.metadata.redirect_uris.some(r=>Cm(r,t)))throw g("invalid_request","redirect_uri is not registered for the client.")}o(N_,"assertRedirectRegistered");function tM(e){let t=j_(e.grant_types),r=e.response_types??[...xp];if(!rM(t))throw new M("invalid_client_metadata","grant_types must be a subset of authorization_code and refresh_token.");if(!nM(r))throw new M("invalid_client_metadata","response_types must be code.");if(!oM(e.scope))throw new M("invalid_client_metadata",`Only the ${ye} scope is supported.`)}o(tM,"assertSupportedDcrRequest");function j_(e){return e===void 0?[...Pp]:Array.from(new Set(e))}o(j_,"normalizeGrantTypes");function rM(e){return e.length===0?!1:e.every(t=>Pp.includes(t))}o(rM,"isSupportedGrantTypes");function nM(e){return e.length===xp.length&&e[0]==="code"}o(nM,"isSupportedResponseTypes");function oM(e){return e===void 0||e===ye}o(oM,"isSupportedDcrScope");function ja(e){if(e===void 0||e===ye)return ye;throw new M("invalid_request",`Only the ${ye} scope is supported.`)}o(ja,"assertSupportedOAuthScope");function po(e,t){let r;try{r=new URL(t)}catch{throw new M("invalid_target","resource must be an absolute URI.")}if(r.hash)throw new M("invalid_target","resource must not include a fragment.");if(r.protocol!=="https:"&&!xe(r))throw new M("invalid_target","resource must use HTTPS except loopback HTTP resources in local development.");let n=ae(e),a=ph(),i=a?[...a.byVirtualServerId.values()].find(s=>new URL(s.routePath,n).toString()===t):void 0;if(!i)throw new M("invalid_target","resource must match a published virtual MCP server.");return i}o(po,"resolveResource");async function D_(e){let t;try{t=W$.parse(e)}catch(l){if(l instanceof u.ZodError){let m=l.issues.some(h=>h.path[0]==="redirect_uris");throw new M(m?"invalid_redirect_uri":"invalid_client_metadata",l.issues[0]?.message??"Client metadata is invalid.",void 0,{cause:l})}throw l}tM(t);for(let l of t.redirect_uris)Na(l,"invalid_redirect_uri");let r=new Date,n=Ae.parse(`dcr:${crypto.randomUUID()}`),a=Bt(r,J$),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:j_(t.grant_types),response_types:["code"],scope:ye,token_endpoint_auth_method:t.token_endpoint_auth_method,client_id_issued_at:i},d={clientId:n,clientName:String(c.client_name),redirectUris:t.redirect_uris,tokenEndpointAuthMethod:t.token_endpoint_auth_method,createdAt:re(r),clientExpiresAt:re(a)};if(t.token_endpoint_auth_method!=="none"){let l=Gt();d.hashedClientSecret=await le(l),d.clientSecretExpiresAt=re(a),c.client_secret=l,c.client_secret_expires_at=s,c.client_secret_issued_at=i}if((await K().registerClient(d)).kind==="already_exists")throw g("invalid_request","OAuth client is already registered.");return c}o(D_,"registerDownstreamClient");var aM="data:,",H_=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);"`,L_=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 iM(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(iM,"safeGatewayConnectHref");function sM(e){return e.some(r=>r.ownerMode==="user"&&r.status!=="active")?"setup":"grant"}o(sM,"deriveMode");function cM(e){return c_({state:e.state,submitOnceAttrs:H_,authorizeAttrs:Ma})}o(cM,"renderActions");function kp(e,t,r){for(let n of e){if(n.ownerMode!=="user"||n.status!==r)continue;let a=iM(n.connectUrl,t);if(a)return a}}o(kp,"firstUserConnectHref");function uM(e){let t=e.connectHref?se`<a class="button button--primary" href="${e.connectHref}" ${L_}>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" ${H_}><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(uM,"renderSetupActions");function dM(e){return e?se`<span class="reconnect-action"><a class="button button--secondary reconnect-button" href="${e}" ${L_}>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>`:Ma}o(dM,"renderReconnectAction");function Tp(e){let t=sM(e.upstreams),r=kp(e.upstreams,e.gatewayOrigin,"not_connected"),n=kp(e.upstreams,e.gatewayOrigin,"reconsent_required"),a=kp(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">${uM({state:e.state,connectHref:i})}</footer>`:se`<footer class="card__footer">${dM(a)}${cM({state:e.state})}</footer>`;return Mr(ar({title:`Authorize access \xB7 ${e.virtualServerDisplayName}`,iconHref:aM,styles:or,headerIcon:Ma,heading:"MCP Gateway",subhead:Ma,body:s,footer:c}))}o(Tp,"renderConsentPage");function lM(e){try{return new URL(e).host}catch{return}}o(lM,"safeUrlHost");function pM(e){if(e.mode==="user-oauth"||e.mode==="shared-oauth")return e.oauth.scopes}o(pM,"readOAuthScopes");function Ap(e){return e!==void 0&&e.length>0}o(Ap,"hasItems");function mM(e){let t=e.registeredConnection.config.serverInfo?.icons;if(Ap(t))return t;let r=e.virtualServer.serverInfo?.icons;return e.virtualServer.connections.length===1&&Ap(r)?r:void 0}o(mM,"readServerIcons");async function fM(e){if(!(e.returnTo===void 0||!e.isUserOwned))return Lu({requestUrl:e.requestUrl,owner:e.userOwner,initiatedBySubjectId:e.transaction.principal.subjectId,upstreamServerId:e.registeredConnection.upstreamServerId,authProfileId:e.registeredConnection.authProfileId,virtualServerId:e.virtualServer.virtualServerId,returnTo:e.returnTo})}o(fM,"readConnectUrl");function yn(e,t){return t===void 0?{}:{[e]:t}}o(yn,"optionalRequirementField");function hM(e){return e.isUserOwned?Nm(e.connection):{connected:!0,status:"active"}}o(hM,"readSetupConnectionStatus");function gM(e){let t=pM(e);return Ap(t)?t:void 0}o(gM,"readScopesRequested");function yM(e){return e.isUserOwned&&"updatedAt"in e.connectionStatus&&e.connectionStatus.updatedAt!==void 0?e.connectionStatus.updatedAt:void 0}o(yM,"readUpdatedAt");function SM(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(xi),prompts:e.virtualServer.catalog.prompts.filter(r=>r.enabled!==!1&&t(r)).map(ki),resources:e.virtualServer.catalog.resources.filter(r=>r.enabled!==!1&&t(r)).map(Ti)}}o(SM,"readVirtualServerCapabilities");async function vM(e){let{authConfig:t,authMode:r,config:n,upstreamServerId:a,authProfileId:i}=e.registeredConnection,s=Oi(r),c=s==="user",d=hM({connection:e.connection,isUserOwned:c}),p=await fM({...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:SM({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer}),...yn("description",n.description),...yn("transportHost",lM(n.transport.baseUrl)),...yn("scopesRequested",gM(t)),...yn("serverIcons",mM({registeredConnection:e.registeredConnection,virtualServer:e.virtualServer})),...yn("connectUrl",p),...yn("updatedAt",yM({connectionStatus:d,isUserOwned:c})),...yn("expiresAt",e.connection?.expiresAt)}}o(vM,"buildSetupRequirement");function B_(e){let t=at().byVirtualServerId.get(e);if(!t)throw g("unknown_virtual_server",`Unknown virtual server: ${e}`);return t}o(B_,"requireVirtualServer");async function Ep(e){let t=B_(e.transaction.virtualServerId),r=dr(e.transaction.principal.subjectId),n=[],a=new Map;for(let c of t.connections)Oi(c.authMode)==="user"&&(a.set(c,n.length),n.push({owner:r,upstreamServerId:c.upstreamServerId,authProfileId:c.authProfileId}));let i=await K().batchGetUpstreamConnections(n),s=[];for(let c of t.connections){let d=Oi(c.authMode)==="user",p=a.get(c);s.push(await vM({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(Ep,"requirementsForSetup");function _M(e){return e.virtualServer.serverInfo?.title??e.virtualServer.serverInfo?.name??e.virtualServer.virtualServerId}o(_M,"readVirtualServerDisplayName");async function Up(e){let t=B_(e.transaction.virtualServerId),r=_M({virtualServer:t}),n=await K().readClient({clientId:e.transaction.clientId}),a=n.kind==="found"?n.client:void 0,i={gatewayOrigin:ae(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(Up,"consentContext");function G_(e){return e.some(t=>t.ownerMode==="user"&&t.status!=="active")}o(G_,"hasUnresolvedUserUpstream");var wM=["mcp_user"],bM="dev-browser-user",RM=["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(" "),CM=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:ei,state:u.string().min(1).optional(),scope:u.literal(ye).default(ye)}),IM=u.enum(["continue","approve","cancel"]).default("continue"),PM=u.object({state:u.string().min(1),decision:IM}),xM=u.object({state:u.string().min(1),apiKey:u.string().min(1)}),Sn=class extends Error{static{o(this,"DownstreamAuthorizeRedirectError")}redirectUri;clientState;errorCode;errorDescription;constructor(t){super(t.errorDescription?`${t.errorCode}: ${t.errorDescription}`:t.errorCode,t.cause===void 0?void 0:{cause:t.cause}),this.name="DownstreamAuthorizeRedirectError",this.redirectUri=t.redirectUri,this.clientState=t.clientState,this.errorCode=t.errorCode,this.errorDescription=t.errorDescription}};function V_(e){return typeof e=="string"&&e.length>0?e:void 0}o(V_,"readQueryString");function kM(e){let t=Array.from(at().byVirtualServerId.values());if(t.length!==1)return;let r=t[0];if(r!==void 0)return ur(r.virtualServerId,e.url)}o(kM,"inferSingleVirtualServerResource");function TM(e,t){let r=V_(e.query.resource);if(t===void 0){if(r!==void 0)return r;let a=kM(e);if(a!==void 0)return a;throw new M("invalid_target",RM)}let n=ur(t,e.url);if(r===void 0||r===n)return n;throw new M("invalid_target","resource must match the scoped OAuth authorization endpoint resource.")}o(TM,"requireAuthorizeResource");async function AM(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await Vs(e,n);if(a.principal)return{principal:a.principal};if(!e.user)return a.evictCookie===void 0?{}:{setCookie:a.evictCookie};let i=g_(e);return{principal:i,setCookie:await qa({principal:i,requestUrl:e.url,virtualServerId:t})}}o(AM,"resolveBrowserPrincipal");async function EM(e,t,r){let n={virtualServerId:t};r!==void 0&&(n.context=r);let a=await Vs(e,n);if(!a.principal)throw g("authentication_required","Authorization setup requires a current browser session.");return a.principal}o(EM,"requireSetupPrincipal");async function F_(e){let t=await Ep({transaction:e.transaction,requestUrl:e.requestUrl,returnTo:`/oauth/setup?state=${encodeURIComponent(e.csrfToken)}`}),r=await Up({transaction:e.transaction,requestUrl:e.requestUrl}),n={kind:"setup_page",html:Tp({state:e.csrfToken,virtualServerId:e.transaction.virtualServerId,upstreams:t,...r})};return e.setCookie!==void 0&&(n.setCookie=e.setCookie),n}o(F_,"renderSetup");function UM(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(UM,"toAuthorizationTransactionClient");async function Op(e,t={}){let r=CM.parse({...e.query,resource:TM(e,t.virtualServerId),state:V_(e.query.state)}),n=ja(r.scope);Na(r.redirect_uri);let a=new Date,i=Ae.parse(r.client_id),s=await Ks(r.client_id,a);N_(s,r.redirect_uri);try{let c=po(e.url,r.resource),d=UM(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&&V(t.context,{eventType:B.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 AM(e,c.virtualServerId,t.context);if(!l){let y=await U_({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 v={kind:"redirect",location:y.browserLoginUrl};return m!==void 0&&(v.setCookie=m),v}let h=await O_({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&&V(t.context,{eventType:B.MCP_OAUTH_AUTHORIZE_AWAITING_SETUP,outcome:"success",virtualServerName:c.virtualServerId,attributes:{clientId:i,scope:n,responseType:r.response_type,subjectId:l.subjectId}}),F_({transaction:h.transaction,csrfToken:h.csrfToken,requestUrl:e.url,setCookie:m})}catch(c){throw OM({redirectUri:r.redirect_uri,clientState:r.state,cause:c})}}o(Op,"authorizeDownstreamClient");function OM(e){if(e.cause instanceof Sn)return e.cause;let t=$M(e.cause);return t?new Sn({redirectUri:e.redirectUri,clientState:e.clientState,errorCode:t.errorCode,errorDescription:t.errorDescription,cause:e.cause}):e.cause}o(OM,"toDownstreamAuthorizeRedirectError");function $M(e){if(e instanceof M)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($M,"mapToOAuthRedirectError");async function Z_(e,t={}){let r=typeof e.query.error=="string"?e.query.error:void 0;if(r){let p=typeof e.query.error_description=="string"?e.query.error_description.slice(0,256):void 0,l=typeof e.query.error_uri=="string"?e.query.error_uri.slice(0,256):void 0;throw t.context?.log.warn({event:"browser_login_callback_idp_error",code:"provider_access_denied",idpError:r,...p===void 0?{}:{idpErrorDescription:p},...l===void 0?{}:{idpErrorUri:l}},"Identity provider redirected browser-login callback with an error"),g("provider_access_denied",p??"The delegated browser login was not completed.")}let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw t.context?.log.warn({event:"browser_login_callback_state_missing",code:"oauth_state_invalid"},"Browser login callback was invoked without a state parameter"),g("oauth_state_invalid","Browser login callback is missing state.");let a=await Fs(n),i={request:e,stateId:a.stateId};t.context!==void 0&&(i.context=t.context);let s=await S_(i),c=await Cp({browserLoginStateToken:n,principal:s}),d=await F_({transaction:c.transaction,csrfToken:c.csrfToken,requestUrl:e.url});return d.setCookie=await qa({principal:s,requestUrl:e.url,virtualServerId:c.transaction.virtualServerId}),d}o(Z_,"completeBrowserLoginCallback");async function K_(e){let t=ke(),r=new URL(e.url);if(!xe(r))throw g("forbidden","Local browser login is only available on loopback HTTP origins.");let n=typeof e.query.state=="string"?e.query.state:void 0;if(!n)throw g("oauth_state_invalid","Local browser login is missing state.");let a=new URL(typeof e.query.redirect_uri=="string"?e.query.redirect_uri:"/oauth/callback",ae(e.url)),i=new URL(ae(e.url)).origin;if(a.origin!==i||a.pathname!=="/oauth/callback")throw g("oauth_callback_mismatch","Local browser login redirect_uri must target this gateway's /oauth/callback route.");a.searchParams.set("state",n);let s={subjectId:ve.parse(bM),roles:wM};return{kind:"redirect",location:a,setCookie:await qa({principal:s,requestUrl:e.url})}}o(K_,"completeLocalDevBrowserLogin");async function J_(e){let t=xM.parse(e.body),r=await $_({browserLoginStateToken:t.state}),n=await y_({apiKey:t.apiKey,virtualServerId:r.virtualServerId}),a=await Cp({browserLoginStateToken:t.state,principal:n});await Rg({apiKey:t.apiKey,principal:n,virtualServerId:a.transaction.virtualServerId});let i=new URL("/oauth/setup",vt(e.request.url));return i.searchParams.set("state",a.csrfToken),{kind:"redirect",location:i,setCookie:await qa({principal:n,requestUrl:e.request.url,virtualServerId:a.transaction.virtualServerId})}}o(J_,"completeApiKeyBrowserLogin");function MM(e){let t=e.method==="POST"?e.body:e.query;return PM.parse(t)}o(MM,"readSetupContinueRequest");async function W_(e){let{state:t,decision:r}=MM({method:e.request.method,query:e.request.query,body:e.body}),n=new Date,a=await Ip({csrfToken:t,now:n}),i=await EM(e.request,a.virtualServerId,e.context);if(r==="cancel")return{kind:"redirect",location:await q_({csrfToken:t,currentBrowserPrincipal:i,now:n})};let s=await M_({csrfToken:t,currentBrowserPrincipal:i,now:n}),c=await Ep({transaction:s,requestUrl:e.request.url,returnTo:`/oauth/setup?state=${encodeURIComponent(t)}`});if(r==="continue"||G_(c)){let d=await Up({transaction:s,requestUrl:e.request.url});return{kind:"setup_page",html:Tp({state:t,virtualServerId:s.virtualServerId,upstreams:c,...d})}}return{kind:"redirect",location:await z_({csrfToken:t,currentBrowserPrincipal:i,now:n})}}o(W_,"continueDownstreamAuthorizeSetup");ue();import{createLocalJWKSet as zM,decodeJwt as qM,errors as Da,jwtVerify as NM}from"jose";var jM=new Set(["authorization_code","refresh_token"]),DM="urn:ietf:params:oauth:client-assertion-type:jwt-bearer",HM=1e4,LM=32*1024,BM=2,Y_=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()}),GM=u.discriminatedUnion("grant_type",[Y_.extend({grant_type:u.literal("authorization_code"),code:u.string().min(1),redirect_uri:u.string().min(1),code_verifier:ti,resource:u.url().optional(),scope:u.literal(ye).optional()}),Y_.extend({grant_type:u.literal("refresh_token"),refresh_token:u.string().min(1),resource:u.url().optional(),scope:u.literal(ye).optional()})]);function VM(e){if(typeof e!="object"||e===null)return;let t=e.grant_type;if(t!==void 0&&(typeof t!="string"||!jM.has(t)))throw new M("unsupported_grant_type",`Grant type "${typeof t=="string"?t:""}" is not supported.`)}o(VM,"assertSupportedGrantType");var FM=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()}),ZM=u.object({keys:u.array(u.record(u.string(),u.unknown())).min(1)}).passthrough();function Q_(){return ke().gateway.accessTokenTtlSeconds}o(Q_,"readAccessTokenTtlSeconds");function KM(){return ke().gateway.refreshTokenTtlSeconds}o(KM,"readRefreshTokenTtlSeconds");function JM(e,t){let r=Q_(),n=Math.max(1,Math.floor((new Date(t).getTime()-e.getTime())/1e3)),a=Math.min(r,n);return{expiresAt:re(Bt(e,a)),expiresIn:a}}o(JM,"calculateAccessTokenExpiresAt");function X_(e){if(!e?.startsWith("Basic "))return{};let t;try{t=atob(e.slice(6))}catch{throw new M("invalid_client","Malformed HTTP Basic client authentication.")}let r=t.indexOf(":");if(r<0)throw new M("invalid_client","Malformed HTTP Basic client authentication.");try{return{clientId:decodeURIComponent(t.slice(0,r)),clientSecret:decodeURIComponent(t.slice(r+1))}}catch{throw new M("invalid_client","Malformed HTTP Basic client authentication.")}}o(X_,"readBasicClientSecret");function ew(e){if(e.basicClientId!==void 0&&e.bodyClientId!==void 0&&e.basicClientId!==e.bodyClientId)throw new M("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=qM(e.clientAssertion);if(typeof r.iss=="string"&&typeof r.sub=="string"&&r.iss===r.sub)return r.iss}catch{throw new M("invalid_client","Malformed private_key_jwt client assertion.")}throw new M("invalid_client","private_key_jwt client assertion must identify the client with matching iss and sub claims.")}throw new M("invalid_client","Client authentication or client_id is required.")}o(ew,"resolveAuthenticatedClientId");function WM(e){if(e.basicClientSecret!==void 0&&e.bodyClientSecret!==void 0)throw new M("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(WM,"resolveClientSecretInput");function YM(e){return e.clientAssertion!==void 0||e.clientAssertionType!==void 0}o(YM,"hasClientAssertion");function QM(e){if(e.requestUrl===void 0)throw new M("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(QM,"buildEndpointAudience");function XM(e){return e instanceof Da.JWTExpired?"expired":e instanceof Da.JWTClaimValidationFailed?"claim":e instanceof Da.JWSSignatureVerificationFailed?"signature":e instanceof Da.JWKSNoMatchingKey?"jwks_no_match":e instanceof Da.JWTInvalid?"invalid":e instanceof u.ZodError?"schema":"other"}o(XM,"readJwtFailureKind");async function ez(e){let{response:t,json:r}=await Rh(e.jwksUri,{headers:{accept:"application/json"}},{context:e.context,maxRedirects:BM,maxResponseBytes:LM,timeoutMs:HM});if(!t.ok)throw new M("invalid_client","Client JWKS could not be fetched.");return ZM.parse(r)}o(ez,"fetchClientJwks");async function tz(e){if(e.clientAssertionType!==DM||e.clientAssertion===void 0)throw new M("invalid_request","private_key_jwt client authentication requires a JWT bearer client_assertion and client_assertion_type.");let t=Ae.parse(e.clientId),r=await Ks(t,e.now);if(r.metadata.token_endpoint_auth_method!=="private_key_jwt")throw new M("invalid_client","Client is not registered for private_key_jwt authentication.");let n=r.metadata.jwks_uri;if(n===void 0)throw new M("invalid_client","Client JWKS URI is required for private_key_jwt authentication.");let a=QM({requestUrl:e.requestUrl,pathname:e.endpointPathname});try{let i=await ez({jwksUri:n,context:e.context});await NM(e.clientAssertion,zM(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:XM(i)},"OAuth private_key_jwt client authentication failed"),new M("invalid_client","Client authentication failed.")}return{method:"private_key_jwt",clientId:t}}o(tz,"verifyPrivateKeyJwtClientAssertion");async function rz(e){let t=Ae.parse(e.clientId);return e.clientSecret===void 0?{method:"none",clientId:t}:{method:e.clientSecretSource==="post"?"client_secret_post":"client_secret_basic",clientId:t,clientSecretHashInput:await le(e.clientSecret)}}o(rz,"buildRuntimeHttpClientAuth");async function tw(e){if(YM({clientAssertion:e.clientAssertion,clientAssertionType:e.clientAssertionType})){if(e.basicClientSecret!==void 0||e.bodyClientSecret!==void 0)throw new M("invalid_request","Use only one client authentication method per request.");return tz(e)}let t=WM({basicClientSecret:e.basicClientSecret,bodyClientSecret:e.bodyClientSecret});return rz({clientId:e.clientId,...t})}o(tw,"resolveRuntimeHttpClientAuth");async function rw(e){VM(e.body);let t=GM.parse(e.body),r=X_(e.authorizationHeader),n=ew({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date,i=await tw({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 nz({parsed:t,clientId:n,clientAuth:i,now:a,requestUrl:e.requestUrl,context:e.context})}o(rw,"exchangeDownstreamToken");async function nz(e){if(e.parsed.grant_type==="authorization_code"){Na(e.parsed.redirect_uri),ja(e.parsed.scope),e.parsed.resource!==void 0&&po(e.requestUrl??e.parsed.resource,e.parsed.resource);let s=Gt(),c=Gt(),d=re(Bt(e.now,KM())),p=JM(e.now,d),l=await K().exchangeAuthorizationCode({clientAuth:e.clientAuth,codeHash:await le(e.parsed.code),redirectUri:e.parsed.redirect_uri,...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},codeChallenge:await Ef(e.parsed.code_verifier),currentRefreshTokenHash:await le(s),accessTokenHash:await le(c),grantExpiresAt:d,accessTokenExpiresAt:p.expiresAt,now:re(e.now)});if(l.kind==="invalid_client")throw new M("invalid_client","Client authentication failed.");if(l.kind==="resource_mismatch")throw new M("invalid_target","Token request resource must match the authorization code resource.");if(l.kind!=="exchanged")throw new M("invalid_grant","Authorization code is invalid, expired, already used, or failed binding validation.");return e.context&&V(e.context,{eventType:B.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}}ja(e.parsed.scope),e.parsed.resource!==void 0&&po(e.requestUrl??e.parsed.resource,e.parsed.resource);let t=Gt(),r=Gt(),n=re(Bt(e.now,Q_())),a=await K().refreshToken({clientAuth:e.clientAuth,currentRefreshTokenHash:await le(e.parsed.refresh_token),nextRefreshTokenHash:await le(t),accessTokenHash:await le(r),...e.parsed.resource===void 0?{}:{resource:e.parsed.resource},accessTokenExpiresAt:n,now:re(e.now)});if(a.kind==="invalid_client")throw new M("invalid_client","Client authentication failed.");if(a.kind==="resource_mismatch")throw new M("invalid_target","Token request resource must match the refresh token grant resource.");if(a.kind!=="rotated")throw new M("invalid_grant","Refresh token is invalid, expired, or revoked.");po(e.requestUrl??a.grant.resource,a.grant.resource);let i=a.accessToken.expiresAt;return e.context&&(V(e.context,{eventType:B.MCP_OAUTH_TOKEN_ISSUED,outcome:"success",attributes:{clientId:e.clientId,grantType:"refresh_token"}}),V(e.context,{eventType:B.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(nz,"exchangeDownstreamTokenWithRuntimeHttp");async function nw(e){let t=FM.parse(e.body),r=X_(e.authorizationHeader),n=ew({basicClientId:r.clientId,bodyClientId:t.client_id,clientAssertion:t.client_assertion}),a=new Date;if((await K().revokeOAuthToken({clientAuth:await tw({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 le(t.token),now:re(a)})).kind==="invalid_client")throw new M("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&&V(e.context,{eventType:B.MCP_OAUTH_TOKEN_REVOKED,outcome:"success",attributes:{clientId:n,...t.token_type_hint===void 0?{}:{tokenTypeHint:t.token_type_hint}}})}o(nw,"revokeDownstreamToken");var oz=64*1024,az=16*1024,iz="text/html; charset=utf-8";function sz(e){let t={};for(let[r,n]of e.entries())t[r]=n;return t}o(sz,"formDataToObject");async function cz(e){return o_(e,{maxBytes:oz,label:"Request body"})}o(cz,"readJsonBody");async function Js(e){return sz(await Gs(e,{maxBytes:az,label:"Request body"}))}o(Js,"readFormBody");async function Ws(e,t,r){let n=ge(r),a=r instanceof u.ZodError?ow(r):void 0,i={code:n??(r instanceof u.ZodError?"invalid_request":"internal_server_error")};return a!==void 0&&(i.detail=a),dt(e,t,i)}o(Ws,"handleProblem");function Ha(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(Ha,"oauthErrorResponse");function uz(e,t){return e.errorCode!=="invalid_client"?{}:t.includeInvalidClientChallenge===!1?{}:{"WWW-Authenticate":'Basic realm="OAuth"'}}o(uz,"readOAuthProtocolHeaders");function dz(e,t){let r=Ke("internal_server_error");return Ha({error:e.errorCode,errorDescription:e.errorCode==="server_error"?r.publicDetail:e.message,status:e.status,headers:uz(e,t)})}o(dz,"oauthProtocolErrorResponse");function lz(e){return e.issues[0]?.path.includes("resource")===!0?"invalid_target":"invalid_request"}o(lz,"readZodOAuthErrorCode");function pz(e){let t={error:lz(e)},r=ow(e);return r!==void 0&&(t.errorDescription=r),Ha(t)}o(pz,"oauthZodErrorResponse");function mz(e){let t=ge(e);if(t===void 0)return;let r=Ke(t);if(r.oauthError===void 0)return;let n={error:r.oauthError,status:hz(r.oauthError)};return r.oauthError==="server_error"?n.errorDescription=r.publicDetail:e instanceof Error?n.errorDescription=e.message:n.errorDescription=r.publicDetail,Ha(n)}o(mz,"oauthGatewayProblemResponse");function fz(){let t={error:"server_error",status:500,errorDescription:Ke("internal_server_error").publicDetail};return Ha(t)}o(fz,"oauthFallbackErrorResponse");function hz(e){switch(e){case"invalid_client":return 401;case"server_error":return 500;default:return 400}}o(hz,"readOAuthStatus");function mo(e,t={}){return e instanceof Sn?gz(e):e instanceof M?dz(e,t):e instanceof u.ZodError?pz(e):mz(e)??fz()}o(mo,"oauthProblemResponse");function jt(e,t,r){let n={event:t},a=!1;if(r instanceof M)n.oauthError=r.errorCode,n.status=r.status,Ye(n,"error",r);else if(r instanceof Sn)n.oauthError=r.errorCode,Ye(n,"error",r);else if(r instanceof u.ZodError){n.code="invalid_request",Ye(n,"error",r);let i=r.issues[0];i&&(n.zodPath=i.path.join("."))}else{let i=ge(r);if(i!==void 0){let s=Ke(i);n.code=i,n.status=s.status,s.oauthError!==void 0&&(n.oauthError=s.oauthError),a=s.status>=500||s.oauthError==="server_error",Ye(n,"error",r)}else a=!0,Ye(n,"error",r)}if(a){let i=r instanceof Error?r:new Error("Non-Error thrown from OAuth handler",{cause:r});e.log.error(n,i.message)}else e.log.warn(n,"OAuth handler rejected the request")}o(jt,"logUnexpectedOAuthHandlerError");function gz(e){let t;try{t=new URL(e.redirectUri)}catch{return Ha({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(gz,"downstreamAuthorizeRedirectErrorResponse");function ow(e){let t=e.issues[0];if(!t)return;let r=t.path.join(".");return r?`${r}: ${t.message}`:t.message}o(ow,"formatZodErrorDetail");function yz(e,t){let r={event:"browser_login_callback_failed",code:ge(t)??"invalid_request"};Ye(r,"error",t),e.log.warn(r,"Browser login callback failed; client received a connection-failure page")}o(yz,"logBrowserLoginCallbackFailure");function $p(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($p,"redirectResultResponse");function Ys(e){if(e.kind==="setup_page"){let t=new Headers({"content-type":iz,"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 $p(e)}o(Ys,"authorizeResultResponse");async function aw(e,t){try{return Response.json(xc(e.url))}catch(r){return jt(t,"oauth_authorization_server_metadata_failed",r),Ws(e,t,r)}}o(aw,"authorizationServerMetadataHandler");async function iw(e,t){try{let r=Te.parse(e.params.virtualServerId),n=Hr(r);return Response.json(Pm({virtualServerId:n.virtualServerId,requestUrl:e.url}))}catch(r){return jt(t,"oauth_authorization_server_metadata_failed",r),Ws(e,t,r)}}o(iw,"scopedAuthorizationServerMetadataHandler");async function sw(e,t){try{let r=await D_(await cz(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"),V(t,{eventType:B.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 jt(t,"oauth_register_failed",r),mo(r)}}o(sw,"registerHandler");async function cw(e,t){try{return Ys(await Op(e,{context:t}))}catch(r){return jt(t,"oauth_authorize_failed",r),mo(r,{includeInvalidClientChallenge:!1})}}o(cw,"authorizeHandler");async function uw(e,t){try{let r=Te.parse(e.params.virtualServerId),n=Hr(r);return Ys(await Op(e,{virtualServerId:n.virtualServerId,context:t}))}catch(r){return jt(t,"oauth_authorize_scoped_failed",r),mo(r,{includeInvalidClientChallenge:!1})}}o(uw,"scopedAuthorizeHandler");async function dw(e,t){try{let r=await Z_(e,{context:t});return t.log.info({event:"browser_login_callback_completed",resultKind:r.kind},"Browser login callback completed; consent setup rendered"),Ys(r)}catch(r){return yz(t,r),Ws(e,t,r)}}o(dw,"callbackHandler");async function lw(e,t){try{return $p(await K_(e))}catch(r){return jt(t,"oauth_dev_login_failed",r),mo(r)}}o(lw,"devLoginHandler");async function pw(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?p_(r,n):Sp(r,400)}return e.method!=="POST"?new Response(null,{status:405,headers:{allow:"GET, POST"}}):$p(await J_({request:e,body:await Js(e)}))}catch(n){return jt(t,"oauth_api_key_login_failed",n),Sp(r)}}o(pw,"apiKeyLoginHandler");async function mw(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 Js(e):void 0,context:t});return Ys(r)}catch(r){return jt(t,"oauth_setup_failed",r),Ws(e,t,r)}}o(mw,"setupHandler");async function fw(e,t){try{return Response.json(await rw({body:await Js(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),{headers:{"cache-control":"no-store",pragma:"no-cache"}})}catch(r){return jt(t,"oauth_token_failed",r),mo(r)}}o(fw,"tokenHandler");async function hw(e,t){try{return await nw({body:await Js(e),authorizationHeader:e.headers.get("authorization"),requestUrl:e.url,context:t}),new Response(null,{status:200,headers:{"cache-control":"no-store"}})}catch(r){return jt(t,"oauth_revoke_failed",r),mo(r)}}o(hw,"revokeHandler");var Sz={connect:"Connect",app_password:"App password",callback_authorization_code:"Callback",callback_provider_error:"Callback",callback_invalid:"Callback",client_metadata:"Client metadata"},gw=new kt("upstream-request");function vz(e){let t=gw.get(e);if(!t)throw g("internal_server_error","Upstream request context has not been set");return t}o(vz,"readUpstreamRequestContext");function _z(e,t){return t.some(r=>r===e)}o(_z,"requestContextMatchesKind");function wz(e){return typeof e=="string"?[e]:e}o(wz,"toExpectedKinds");function vn(e,t){gw.set(e,t)}o(vn,"setUpstreamRequestContext");function _n(e,t){let r=vz(e),n=wz(t);if(!_z(r.kind,n)){let a=Sz[n[0]];throw g("internal_server_error",`${a} request context has not been set`)}return r}o(_n,"requireUpstreamRequestContext");function yw(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(yw,"renderAppPassword");function Sw(e){return se`<p data-gateway-error-code="${e.code}">${e.body}</p>`}o(Sw,"renderBrowserResult");var bz="text/html; charset=utf-8",Rz="none";function vw(e){let t=hn(e.host);return ar({title:e.title,iconHref:t,styles:or,headerIcon:gn({iconHref:t,fallbackIconHref:fn}),heading:e.title,subhead:"",body:Sw({body:e.body,code:e.code??Rz}),footer:""})}o(vw,"browserResultHtml");function _w(e,t=200){return new Response(Mr(e),{status:t,headers:{"content-type":bz,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(_w,"browserResultResponse");function Qs(e){return _w(vw(e))}o(Qs,"browserConnectionSuccessResponse");function fo(e,t){let r=cm(t);return _w(vw({host:e,title:r.title,body:r.body,code:t}),400)}o(fo,"browserConnectionFailureResponse");function Mp(e){try{return new URL(e).host}catch{return""}}o(Mp,"safeHostFromUrl");var Cz="text/html; charset=utf-8",Iz=16*1024;function Pz(e,t=200){return new Response(Mr(e),{status:t,headers:{"content-type":Cz,"cache-control":"no-store","referrer-policy":"no-referrer","x-frame-options":"DENY"}})}o(Pz,"htmlResponse");function xz(e,t){return Response.redirect(new URL(t,e).toString(),302)}o(xz,"safeRedirect");function kz(e){if(!e)throw g("oauth_state_invalid","App password capture requires a signed browser ticket.");return e}o(kz,"requireBrowserTicket");function Tz(e,t){return[e.ownerMode!=="user"||e.upstreamServerId!==t.upstreamServerId||t.virtualServerId!==void 0&&e.virtualServerId!==t.virtualServerId].every(n=>!n)}o(Tz,"appPasswordTicketMatchesTarget");async function ww(e){let t=kz(e.browserTicket),r=await Mi(t);if(!Tz(r,e))throw g("oauth_callback_mismatch","App password capture ticket did not match the requested upstream flow.");return{upstreamServerId:e.upstreamServerId,authProfileId:r.authProfileId,virtualServerId:r.virtualServerId,browserTicket:t,ticket:r}}o(ww,"readAppPasswordTarget");function Az(e,t){let r=Ku(e.upstreamServerId,e.authProfileId),n=`/auth/connections/${encodeURIComponent(e.upstreamServerId)}/app-password`,a=hn(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 Pz(ar({title:"Connect upstream",iconHref:a,styles:or,headerIcon:gn({iconHref:a,fallbackIconHref:fn}),heading:"Connect upstream",subhead:se`<p class="card__subtitle">Enter the per-user credential for this approved upstream.</p>`,body:yw({action:n,browserTicket:e.browserTicket,fields:i}),footer:""}))}o(Az,"renderCaptureForm");function Xs(e,t){let r=e.get(t);if(typeof r!="string"||r.length===0)throw g("invalid_request",`Missing form field: ${t}`);return r}o(Xs,"readRequiredFormValue");function Ez(e){return{upstreamServerId:e.upstreamServerId,...e.virtualServerId===void 0?{}:{virtualServerId:e.virtualServerId},...e.browserTicket===void 0?{}:{browserTicket:e.browserTicket}}}o(Ez,"readCaptureFormTargetInput");async function Uz(e,t){return Az(await ww(Ez(e)),t)}o(Uz,"handleCaptureFormRequest");async function Oz(e){let t=await Gs(e.request,{maxBytes:Iz,label:"App password request body"});return{form:t,target:await ww({upstreamServerId:e.upstreamServerId,browserTicket:Xs(t,"browserTicket")})}}o(Oz,"readSubmittedAppPasswordTarget");async function $z(e){let t=An(e.target.ticket);if(await zi(e.target.ticket),Ku(e.target.upstreamServerId,e.target.authProfileId).kind==="bearer_token"){await Ni({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,token:Xs(e.form,"token")});return}await Wh({owner:t,initiatedBySubjectId:e.target.ticket.initiatedBySubjectId,upstreamServerId:e.target.upstreamServerId,authProfileId:e.target.authProfileId,username:Xs(e.form,"username"),appPassword:Xs(e.form,"appPassword")})}o($z,"saveSubmittedAppPasswordCredential");function Mz(e,t){return t.ticket.returnTo?xz(e,t.ticket.returnTo):Qs({host:Mp(e),title:"Connection complete",body:"The upstream credential was saved. Return to your MCP client and retry the request."})}o(Mz,"appPasswordSuccessResponse");async function zz(e){let t=await Oz({request:e.request,upstreamServerId:e.appPasswordRequest.upstreamServerId});return await $z(t),Mz(e.request.url,t.target)}o(zz,"handleAppPasswordSubmission");function qz(){return new Response(null,{status:405,headers:{Allow:"GET, POST"}})}o(qz,"methodNotAllowedResponse");function Nz(e,t){let r=ge(t);return fo(e,Wa(r)?r:"oauth_state_invalid")}o(Nz,"appPasswordFailureResponse");async function jz(e){let t=Mp(e.request.url);switch(e.request.method){case"GET":return Uz(e.appPasswordRequest,t);case"POST":return zz(e);default:return qz()}}o(jz,"handleAppPasswordMethod");async function zp(e,t){let r=_n(t,"app_password");try{return await jz({request:e,appPasswordRequest:r})}catch(n){return Nz(Mp(e.url),n)}}o(zp,"appPasswordHandler");var Dz=["callback_authorization_code","callback_provider_error","callback_invalid"];function Hz(e){return"cause"in e?e.cause:void 0}o(Hz,"readErrorCause");function Lz(e){return e.stack?.split(`
|
|
61
|
+
`).slice(1,4).map(t=>t.trim()).join(" | ")}o(Lz,"readFirstStackFrame");function bw(e,t,r){r instanceof Error&&(e[`${t}Name`]=r.name,e[`${t}Message`]=r.message,e[`${t}StackFrame`]=Lz(r))}o(bw,"addErrorAttributes");function Rw(e){try{return new URL(e).host}catch{return""}}o(Rw,"safeHostFromUrl");function Bz(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"),V(e,{eventType:B.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:t.upstreamServerId,reasonCode:"provider_access_denied",reasonClass:"auth",attributes:{error:t.error,errorDescription:t.errorDescription}}),fo(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"),fo(r,"oauth_state_invalid");case"callback_authorization_code":return t}}o(Bz,"requireAuthorizationCallbackRequest");function Gz(e,t){V(e,{eventType:B.MCP_AUTH_UPSTREAM_CALLBACK_RECEIVED,outcome:"success",upstreamServerName:t.upstreamServerId})}o(Gz,"emitCallbackReceivedAnalyticsEvent");function Vz(e,t){V(e,{eventType:B.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_SUCCEEDED,outcome:"success",upstreamServerName:t.upstreamServerId,virtualServerName:t.virtualServerId})}o(Vz,"emitTokenExchangeSucceededAnalyticsEvent");function Fz(e,t){if(t.returnTo){let r=t.returnOrigin??e.url;return Response.redirect(new URL(t.returnTo,r).toString(),302)}return Qs({host:Rw(e.url),title:"Connection complete",body:"The upstream authorization flow completed successfully. You can return to your MCP client."})}o(Fz,"buildSuccessfulCallbackResponse");function Zz(e){let t={detail:e instanceof Error?e.message:void 0};return bw(t,"error",e),e instanceof Error&&bw(t,"cause",Hz(e)),t}o(Zz,"buildTokenExchangeFailureAttributes");function Kz(e){V(e.context,{eventType:B.MCP_AUTH_UPSTREAM_TOKEN_EXCHANGE_FAILED,outcome:"failure",upstreamServerName:e.callbackRequest.upstreamServerId,reasonCode:ge(e.error)??"token_exchange_failed",reasonClass:"auth",errorType:e.error instanceof Error?e.error.name:"unknown",attributes:Zz(e.error)})}o(Kz,"emitTokenExchangeFailedAnalyticsEvent");function Jz(e,t){let r=ge(t);return fo(e,Wa(r)?r:"upstream_token_exchange_failed")}o(Jz,"tokenExchangeFailureResponse");async function qp(e,t){let r=_n(t,Dz),n=Rw(e.url),a=Bz(t,r,n);if(a instanceof Response)return a;Gz(t,a);try{let i=await Ig({request:e,callbackRequest:a});return Vz(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"),Fz(e,i)}catch(i){let s={event:"upstream_oauth_token_exchange_failed",code:ge(i)??"upstream_token_exchange_failed",upstreamServerId:a.upstreamServerId};return Ye(s,"error",i),t.log.warn(s,"Upstream OAuth token exchange failed; user shown connection-failure page"),Kz({context:t,callbackRequest:a,error:i}),Jz(n,i)}}o(qp,"callbackHandler");function Wz(e){let t=ge(e);return t==="unknown_upstream_server"?t:"not_found"}o(Wz,"clientMetadataProblemCode");function Yz(e){return(e instanceof Error?e.message:void 0)??"The requested upstream client metadata document was not found."}o(Yz,"clientMetadataProblemDetail");async function Cw(e,t){let r=_n(t,"connect"),n=await Cg({request:e,connectRequest:r});if(V(t,{eventType:B.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 vr({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(Cw,"connectHandler");async function Iw(e,t){let r=_n(t,"client_metadata");try{let n=dg(e.url),a=lg(n,r.upstreamServerId,r.authProfileId);return Response.json(a)}catch(n){let a=Wz(n),i=n instanceof Error?n.message:String(n);return t.log.warn({event:"oauth_client_metadata_request_failed",code:a,upstreamServerId:r.upstreamServerId,authProfileId:r.authProfileId,errorMessage:i},"Failed to serve OAuth client metadata document for upstream connection"),dt(e,t,{code:a,detail:Yz(n)})}}o(Iw,"oauthClientMetadataHandler");function ir(e){if(typeof e=="string"&&e.length!==0)return e}o(ir,"readOptionalQueryString");function Qz(e,t){let r=e.params[t];if(typeof r!="string"||r.length===0)throw g("internal_server_error",`Validated path parameter ${t} is missing`);return r}o(Qz,"requirePathString");function Pw(e){let t=ir(e);return t?Te.parse(t):void 0}o(Pw,"readOptionalVirtualServerId");function Xz(e,t){let r=ir(e);return r?We.parse(r):Nn(t,"user-oauth")}o(Xz,"readOptionalAuthProfileId");function eq(e){let t=Pw(e);if(!t)throw g("invalid_request","virtualServerId query parameter is required.");return t}o(eq,"readRequiredVirtualServerId");function tq(e){let t=ir(e.query.browserTicket);return t===void 0?{}:{browserTicket:t}}o(tq,"readOptionalBrowserTicket");function rq(e){let t=ii(ir(e));return t===void 0?{}:{returnTo:t}}o(rq,"readOptionalReturnTo");function nq(e){let t=Pw(e.query.virtualServerId);return t===void 0?{}:{virtualServerId:t}}o(nq,"readOptionalVirtualServerIdContext");function oq(e){let t=ir(e.query.error_description);return t===void 0?{}:{errorDescription:t}}o(oq,"readOptionalProviderErrorDescription");function aq(e){let t=At(e.authMode);if(t.connectSupport!=="none")return e;throw g("invalid_request",t.connectUnsupportedDetail??"This upstream does not support browser connection flows.")}o(aq,"requireConnectableRouteAuth");function iq(e,t,r,n){let a=Bs(e,t);if(a.ownerMode==="none"||a.authMode==="shared-secret")throw g("invalid_request","Static-secret upstreams do not support browser connection flows.");return{kind:"connect",...a,...n===void 0?{}:{returnTo:n},redirect:r}}o(iq,"buildConnectContextForPrincipal");function sq(e,t,r){let n=An(t),a=At(e.authMode);if(n.mode!==a.ownerMode)throw g("oauth_callback_mismatch","Browser connect ticket did not match the requested upstream flow");return{kind:"connect",...e,...t.returnTo===void 0?{}:{returnTo:t.returnTo},owner:n,initiatedBySubjectId:t.initiatedBySubjectId,redirect:r}}o(sq,"buildConnectContextForTicket");async function cq(e,t){let r=aq(t_(t,eq(e.query.virtualServerId))),n=e.query.redirect==="true",a=ir(e.query.browserTicket);if(e.user){if(a)throw g("invalid_request","Use either an authenticated gateway request or a browser connect ticket, not both.");let s=xn(e.user,e.url);return iq(r,s,n,rq(e.query.returnTo).returnTo)}if(!a)throw g("authentication_required","Authentication is required to start the upstream connection flow.");let i=await Mi(a);if(i.ownerMode!==r.ownerMode||i.upstreamServerId!==r.upstreamServerId||i.authProfileId!==r.authProfileId||i.virtualServerId!==r.virtualServerId)throw g("oauth_callback_mismatch","Browser connect ticket did not match the requested upstream flow");return await zi(i),sq(r,i,n)}o(cq,"resolveConnectContext");async function uq(e,t,r){let n=Je.parse(Qz(e,"connection"));switch(r){case"connect":vn(t,await cq(e,n));return;case"app_password":vn(t,{kind:"app_password",upstreamServerId:n,...nq(e),...tq(e)});return;case"callback":{let a=ir(e.query.error);if(a){vn(t,{kind:"callback_provider_error",upstreamServerId:n,error:a,...oq(e)});return}let i=ir(e.query.code),s=ir(e.query.state);if(i&&s){vn(t,{kind:"callback_authorization_code",upstreamServerId:n,code:i,state:s});return}vn(t,{kind:"callback_invalid",upstreamServerId:n});return}case"client_metadata":vn(t,{kind:"client_metadata",upstreamServerId:n,authProfileId:Xz(e.query.authProfileId,n)});return}}o(uq,"resolveUpstreamRequestInbound");async function dq(e,t,r){try{await uq(e,t,r);return}catch(n){let a=ge(n);if(!a)throw n;let i=n instanceof Error?n.message:void 0;return dt(e,t,{code:a,...i===void 0?{}:{detail:i}})}}o(dq,"applyUpstreamRequestContext");function La(e,t){return o(async(n,a)=>{let i=await dq(n,a,e);return i||t(n,a)},"wrapped")}o(La,"withUpstreamRequestContext");var lq={"access-control-allow-origin":"*","access-control-allow-methods":"GET, OPTIONS","access-control-allow-headers":"content-type, authorization","access-control-max-age":"86400"};function pq(){return new Response(null,{status:204,headers:lq})}o(pq,"buildWellKnownPreflightResponse");function mq(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(mq,"withWellKnownCorsHeaders");function Np(e){return async(t,r)=>t.method==="OPTIONS"?pq():mq(await e(t,r))}o(Np,"wrapWellKnownHandler");var fq=[{routeName:"oauth_as_metadata",path:"/.well-known/oauth-authorization-server",methods:["GET","OPTIONS"],handler:Np(aw),corsPolicy:"anything-goes"},{routeName:"oauth_as_metadata_scoped",path:"/.well-known/oauth-authorization-server/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:Np(iw),corsPolicy:"anything-goes"},{routeName:"oauth_protected_resource_metadata",path:"/.well-known/oauth-protected-resource/mcp/:virtualServerId",methods:["GET","OPTIONS"],handler:Np(xm),corsPolicy:"anything-goes"},{routeName:"oauth_register",path:"/oauth/register",methods:["POST"],handler:sw},{routeName:"oauth_authorize",path:"/oauth/authorize",methods:["GET"],handler:cw},{routeName:"oauth_authorize_scoped",path:"/oauth/authorize/mcp/:virtualServerId",methods:["GET"],handler:uw},{routeName:"oauth_callback",path:"/oauth/callback",methods:["GET"],handler:dw},{routeName:"oauth_dev_login",path:"/oauth/dev-login",methods:["GET"],handler:lw},{routeName:"oauth_api_key_login",path:"/oauth/api-key-login",methods:["GET","POST"],handler:pw},{routeName:"oauth_setup",path:"/oauth/setup",methods:["GET","POST"],handler:mw},{routeName:"oauth_token",path:"/oauth/token",methods:["POST"],handler:fw},{routeName:"oauth_revoke",path:"/oauth/revoke",methods:["POST"],handler:hw},{routeName:"upstream_client_metadata",path:"/.well-known/oauth-client/:connection",methods:["GET"],handler:La("client_metadata",Iw)},{routeName:"upstream_connect",path:"/auth/connections/:connection/connect",methods:["GET"],handler:La("connect",Cw)},{routeName:"upstream_callback",path:"/auth/connections/:connection/callback",methods:["GET"],handler:La("callback",qp)},{routeName:"upstream_app_password",path:"/auth/connections/:connection/app-password",methods:["GET","POST"],handler:La("app_password",zp)}];function xw(e){return e?.some(Yc)??!1}o(xw,"shouldRegisterMcpGatewayInternalRoutes");function hq(e){let t=Nf(e.policies);if(!t){let r=[...Wc].map(n=>`\`${n}\``).join(", ");throw new de(`MCP gateway: could not find an MCP authorization policy in policies.json. Add one of [${r}] and reference it on your MCP routes.`)}return lh(zu({routes:e.routes,policies:e.policies})),t.config}o(hq,"initializeMcpGatewayState");function gq(e,t,r){return async(n,a)=>{let i=a;Pn(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(gq,"wrapInternalHandler");function kw(e,t){let r,n=o(()=>(r===void 0&&(r=hq(t)),r),"readOAuthConfig");for(let a of fq){let i=gq(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(kw,"registerMcpGatewayInternalRoutes");function Tw(e){dh(e)}o(Tw,"configureLazyMcpGatewayState");var jp=class extends Jp{static{o(this,"McpGatewayPlugin")}registerRoutes(t){let r=t.parsedRouteData;if(!r||!xw(r.policies))return;let n={routes:r.routes,policies:r.policies};Tw(n),kw(t.router,n)}};export{Zc as McpAuth0OAuthInboundPolicy,jp as McpGatewayPlugin,Kc as McpOAuthInboundPolicy,gp as McpUpstreamConnectionInboundPolicy,o$ as McpVirtualServerHandler,Ox as mcpUpstreamHandler};
|
|
64
62
|
//# sourceMappingURL=index.js.map
|