@zuplo/runtime 6.59.7 → 6.59.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -22,8 +22,8 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- var ge=Object.create;var P=Object.defineProperty;var de=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Ee=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty;var r=(e,t)=>P(e,"name",{value:t,configurable:!0});var ot=(e,t)=>()=>(e&&(t=e(e=0)),t);var it=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),st=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},j=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of _e(t))!he.call(e,o)&&o!==n&&P(e,o,{get:()=>t[o],enumerable:!(s=de(t,o))||s.enumerable});return e};var ct=(e,t,n)=>(n=e!=null?ge(Ee(e)):{},j(t||!e||!e.__esModule?P(n,"default",{value:e,enumerable:!0}):n,e)),lt=e=>j(P({},"__esModule",{value:!0}),e);var W=class extends Error{static{r(this,"SystemError")}constructor(t,n){super(t,n),this.name="InternalError"}},y=class extends Error{static{r(this,"RuntimeError")}extensionMembers;constructor(t,n){typeof t=="string"?super(t,n):(super(t.message,n),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}},q=class extends y{static{r(this,"ConfigurationError")}constructor(t,n){super(t,n),this.name="ConfigurationError"}};var ft="zuplo-request-id",me="zp-rid",Oe="zp-body-removed",ye="cf-ray",gt="x-forwarded-scheme",dt="x-forwarded-proto",_t="x-scheme",Re="cf-ipcity",be="cf-ipcontinent",Ae="cf-ipcountry",xe="cf-iplongitude",Le="cf-iplatitude",Et="cf-region",ht="cf-region-code",mt="cf-metro-code",Ot="cf-postal-code",yt="cf-timezone",Rt="zp-ipcity",bt="zp-ipcontinent",At="zp-ipcountry",xt="zp-iplongitude",Lt="zp-iplatitude",Te="zp-asn",Pe="zp-asorg",Ie="zp-colo",Ce="zp-postalcode",Se="zp-metrocode",we="zp-region",Ue="zp-regioncode",Ne="zp-timezone",Tt="zp-http-protocol",N="zp-local-service",De="x-akamai-edgescape",Pt=[De,N],It=[Re,be,Ae,xe,Le,Te,Pe,Ie,Ce,Se,we,Ue,Ne],Ct=["zp-","cf-"],St=[me,ye,Oe];var wt=Symbol("zuplo_meters"),Ut=Symbol("zuplo_dynamic_meters"),Nt="system-logger";var Me=!1;function L(e,t){return{open:`\x1B[${e.join(";")}m`,close:`\x1B[${t}m`,regexp:new RegExp(`\\x1b\\[${t}m`,"g")}}r(L,"code");function T(e,t){return Me?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}r(T,"run");function ze(e){return T(e,L([31],39))}r(ze,"red");function ve(e){return T(e,L([32],39))}r(ve,"green");function He(e){return T(e,L([33],39))}r(He,"yellow");function Ze(e){return T(e,L([34],39))}r(Ze,"blue");function Fe(e){return T(e,L([35],39))}r(Fe,"magenta");function Ge(e){return T(e,L([36],39))}r(Ge,"cyan");var Mt=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");var J=[ze,ve,He,Ze,Fe,Ge];function $e(e){let t=0,n=e.length,s=0;if(n>0)for(;s<n;)t=(t<<5)-t+e.charCodeAt(s++)|0;return t}r($e,"hashCode");function K(e){let t=Math.abs($e(e));return J[t%J.length]}r(K,"generateColor");function X(e,t,...n){let s=0,o=n.length,u=String(t).replace(/%[sdjoO%]/g,i=>{if(i==="%%")return"%";if(s>=o)return i;switch(i){case"%s":return String(n[s++]);case"%d":return Number(n[s++]).toString();case"%o":return e(n[s++]).split(`
26
- `).map(l=>l.trim()).join(" ");case"%O":return e(n[s++]);case"%j":try{return JSON.stringify(n[s++])}catch{return"[Circular]"}default:return i}});for(let i of n.splice(s))i===null||!(typeof i=="object"&&i!==null)?u+=" "+i:u+=" "+e(i);return u}r(X,"format");function R(e,t,n,s){let o={seen:[],stylize:Ve,showHidden:t??!1,depth:n??2,colors:s??!1,customInspect:!0};return o.colors&&(o.stylize=Be),w(o,e,o.depth)}r(R,"inspect");R.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};R.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Ve(e,t){return e}r(Ve,"stylizeNoColor");function ke(e){return typeof e=="boolean"}r(ke,"isBoolean");function ee(e){return e===void 0}r(ee,"isUndefined");function Be(e,t){let n=R.styles[t];return n?"\x1B["+R.colors[n][0]+"m"+e+"\x1B["+R.colors[n][1]+"m":e}r(Be,"stylizeWithColor");function D(e){return typeof e=="function"}r(D,"isFunction");function te(e){return typeof e=="string"}r(te,"isString");function Ye(e){return typeof e=="number"}r(Ye,"isNumber");function ne(e){return e===null}r(ne,"isNull");function re(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r(re,"hasOwn");function M(e){return Z(e)&&F(e)==="[object RegExp]"}r(M,"isRegExp");function Z(e){return typeof e=="object"&&e!==null}r(Z,"isObject");function z(e){return Z(e)&&(F(e)==="[object Error]"||e instanceof Error)}r(z,"isError");function Q(e){return Z(e)&&F(e)==="[object Date]"}r(Q,"isDate");function F(e){return Object.prototype.toString.call(e)}r(F,"objectToString");function je(e){let t={};return e.forEach(function(n,s){t[n]=!0}),t}r(je,"arrayToHash");function We(e,t,n,s,o){let u=[];for(let i=0,l=t.length;i<l;++i)re(t,String(i))?u.push(H(e,t,n,s,String(i),!0)):u.push("");return o.forEach(function(i){i.match(/^\d+$/)||u.push(H(e,t,n,s,i,!0))}),u}r(We,"formatArray");function v(e){return"["+Error.prototype.toString.call(e)+"]"}r(v,"formatError");function w(e,t,n){if(e.customInspect&&t&&D(t.inspect)&&t.inspect!==R&&!(t.constructor&&t.constructor.prototype===t)){let a=t.inspect(n,e);return te(a)||(a=w(e,a,n)),a}let s=qe(e,t);if(s)return s;let o=Object.keys(t),u=je(o);try{e.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(t))}catch{}if(z(t)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return v(t);if(o.length===0){if(D(t)){let a=t.name?": "+t.name:"";return e.stylize("[Function"+a+"]","special")}if(M(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(Q(t))return e.stylize(Date.prototype.toString.call(t),"date");if(z(t))return v(t)}let i="",l=!1,p=["{","}"];if(Array.isArray(t)&&(l=!0,p=["[","]"]),D(t)&&(i=" [Function"+(t.name?": "+t.name:"")+"]"),M(t)&&(i=" "+RegExp.prototype.toString.call(t)),Q(t)&&(i=" "+Date.prototype.toUTCString.call(t)),z(t)&&(i=" "+v(t)),o.length===0&&(!l||t.length==0))return p[0]+i+p[1];if(n<0)return M(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);let c;return l?c=We(e,t,n,u,o):c=o.map(function(a){return H(e,t,n,u,a,l)}),e.seen.pop(),Je(c,i,p)}r(w,"formatValue");function H(e,t,n,s,o,u){let i,l,p;p={value:void 0};try{p.value=t[o]}catch{}try{Object.getOwnPropertyDescriptor&&(p=Object.getOwnPropertyDescriptor(t,o)||p)}catch{}if(p.get?p.set?l=e.stylize("[Getter/Setter]","special"):l=e.stylize("[Getter]","special"):p.set&&(l=e.stylize("[Setter]","special")),re(s,o)||(i="["+o+"]"),l||(e.seen.indexOf(p.value)<0?(ne(n)?l=w(e,p.value,null):l=w(e,p.value,n-1),l.indexOf(`
25
+ var de=Object.create;var P=Object.defineProperty;var ge=Object.getOwnPropertyDescriptor;var _e=Object.getOwnPropertyNames;var Ee=Object.getPrototypeOf,he=Object.prototype.hasOwnProperty;var r=(e,t)=>P(e,"name",{value:t,configurable:!0});var ot=(e,t)=>()=>(e&&(t=e(e=0)),t);var it=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),st=(e,t)=>{for(var n in t)P(e,n,{get:t[n],enumerable:!0})},j=(e,t,n,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of _e(t))!he.call(e,o)&&o!==n&&P(e,o,{get:()=>t[o],enumerable:!(s=ge(t,o))||s.enumerable});return e};var ct=(e,t,n)=>(n=e!=null?de(Ee(e)):{},j(t||!e||!e.__esModule?P(n,"default",{value:e,enumerable:!0}):n,e)),lt=e=>j(P({},"__esModule",{value:!0}),e);var W=class extends Error{static{r(this,"SystemError")}constructor(t,n){super(t,n),this.name="InternalError"}},y=class extends Error{static{r(this,"RuntimeError")}extensionMembers;constructor(t,n){typeof t=="string"?super(t,n):(super(t.message,n),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}},q=class extends y{static{r(this,"ConfigurationError")}constructor(t,n){super(t,n),this.name="ConfigurationError"}};var ft="zuplo-request-id",me="zp-rid",Oe="zp-body-removed",ye="cf-ray",dt="x-forwarded-scheme",gt="x-forwarded-proto",_t="x-scheme",Re="cf-ipcity",be="cf-ipcontinent",Ae="cf-ipcountry",xe="cf-iplongitude",Le="cf-iplatitude",Et="cf-region",ht="cf-region-code",mt="cf-metro-code",Ot="cf-postal-code",yt="cf-timezone",Rt="zp-ipcity",bt="zp-ipcontinent",At="zp-ipcountry",xt="zp-iplongitude",Lt="zp-iplatitude",Te="zp-asn",Pe="zp-asorg",Ie="zp-colo",Ce="zp-postalcode",Se="zp-metrocode",we="zp-region",Ue="zp-regioncode",Ne="zp-timezone",Tt="zp-http-protocol",N="zp-local-service",De="x-akamai-edgescape",Pt=[De,N],It=[Re,be,Ae,xe,Le,Te,Pe,Ie,Ce,Se,we,Ue,Ne],Ct=["zp-","cf-"],St=[me,ye,Oe];var wt=Symbol("zuplo_meters"),Ut=Symbol("zuplo_dynamic_meters"),Nt="system-logger";var Me=!1;function L(e,t){return{open:`\x1B[${e.join(";")}m`,close:`\x1B[${t}m`,regexp:new RegExp(`\\x1b\\[${t}m`,"g")}}r(L,"code");function T(e,t){return Me?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}r(T,"run");function ve(e){return T(e,L([31],39))}r(ve,"red");function ze(e){return T(e,L([32],39))}r(ze,"green");function He(e){return T(e,L([33],39))}r(He,"yellow");function Ze(e){return T(e,L([34],39))}r(Ze,"blue");function Fe(e){return T(e,L([35],39))}r(Fe,"magenta");function Ge(e){return T(e,L([36],39))}r(Ge,"cyan");var Mt=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");var J=[ve,ze,He,Ze,Fe,Ge];function $e(e){let t=0,n=e.length,s=0;if(n>0)for(;s<n;)t=(t<<5)-t+e.charCodeAt(s++)|0;return t}r($e,"hashCode");function K(e){let t=Math.abs($e(e));return J[t%J.length]}r(K,"generateColor");function X(e,t,...n){let s=0,o=n.length,u=String(t).replace(/%[sdjoO%]/g,i=>{if(i==="%%")return"%";if(s>=o)return i;switch(i){case"%s":return String(n[s++]);case"%d":return Number(n[s++]).toString();case"%o":return e(n[s++]).split(`
26
+ `).map(l=>l.trim()).join(" ");case"%O":return e(n[s++]);case"%j":try{return JSON.stringify(n[s++])}catch{return"[Circular]"}default:return i}});for(let i of n.splice(s))i===null||!(typeof i=="object"&&i!==null)?u+=" "+i:u+=" "+e(i);return u}r(X,"format");function R(e,t,n,s){let o={seen:[],stylize:Ve,showHidden:t??!1,depth:n??2,colors:s??!1,customInspect:!0};return o.colors&&(o.stylize=Be),w(o,e,o.depth)}r(R,"inspect");R.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};R.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function Ve(e,t){return e}r(Ve,"stylizeNoColor");function ke(e){return typeof e=="boolean"}r(ke,"isBoolean");function ee(e){return e===void 0}r(ee,"isUndefined");function Be(e,t){let n=R.styles[t];return n?"\x1B["+R.colors[n][0]+"m"+e+"\x1B["+R.colors[n][1]+"m":e}r(Be,"stylizeWithColor");function D(e){return typeof e=="function"}r(D,"isFunction");function te(e){return typeof e=="string"}r(te,"isString");function Ye(e){return typeof e=="number"}r(Ye,"isNumber");function ne(e){return e===null}r(ne,"isNull");function re(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r(re,"hasOwn");function M(e){return Z(e)&&F(e)==="[object RegExp]"}r(M,"isRegExp");function Z(e){return typeof e=="object"&&e!==null}r(Z,"isObject");function v(e){return Z(e)&&(F(e)==="[object Error]"||e instanceof Error)}r(v,"isError");function Q(e){return Z(e)&&F(e)==="[object Date]"}r(Q,"isDate");function F(e){return Object.prototype.toString.call(e)}r(F,"objectToString");function je(e){let t={};return e.forEach(function(n,s){t[n]=!0}),t}r(je,"arrayToHash");function We(e,t,n,s,o){let u=[];for(let i=0,l=t.length;i<l;++i)re(t,String(i))?u.push(H(e,t,n,s,String(i),!0)):u.push("");return o.forEach(function(i){i.match(/^\d+$/)||u.push(H(e,t,n,s,i,!0))}),u}r(We,"formatArray");function z(e){return"["+Error.prototype.toString.call(e)+"]"}r(z,"formatError");function w(e,t,n){if(e.customInspect&&t&&D(t.inspect)&&t.inspect!==R&&!(t.constructor&&t.constructor.prototype===t)){let a=t.inspect(n,e);return te(a)||(a=w(e,a,n)),a}let s=qe(e,t);if(s)return s;let o=Object.keys(t),u=je(o);try{e.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(t))}catch{}if(v(t)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return z(t);if(o.length===0){if(D(t)){let a=t.name?": "+t.name:"";return e.stylize("[Function"+a+"]","special")}if(M(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(Q(t))return e.stylize(Date.prototype.toString.call(t),"date");if(v(t))return z(t)}let i="",l=!1,p=["{","}"];if(Array.isArray(t)&&(l=!0,p=["[","]"]),D(t)&&(i=" [Function"+(t.name?": "+t.name:"")+"]"),M(t)&&(i=" "+RegExp.prototype.toString.call(t)),Q(t)&&(i=" "+Date.prototype.toUTCString.call(t)),v(t)&&(i=" "+z(t)),o.length===0&&(!l||t.length==0))return p[0]+i+p[1];if(n<0)return M(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);let c;return l?c=We(e,t,n,u,o):c=o.map(function(a){return H(e,t,n,u,a,l)}),e.seen.pop(),Je(c,i,p)}r(w,"formatValue");function H(e,t,n,s,o,u){let i,l,p;p={value:void 0};try{p.value=t[o]}catch{}try{Object.getOwnPropertyDescriptor&&(p=Object.getOwnPropertyDescriptor(t,o)||p)}catch{}if(p.get?p.set?l=e.stylize("[Getter/Setter]","special"):l=e.stylize("[Getter]","special"):p.set&&(l=e.stylize("[Setter]","special")),re(s,o)||(i="["+o+"]"),l||(e.seen.indexOf(p.value)<0?(ne(n)?l=w(e,p.value,null):l=w(e,p.value,n-1),l.indexOf(`
27
27
  `)>-1&&(u?l=l.split(`
28
28
  `).map(function(c){return" "+c}).join(`
29
29
  `).substr(2):l=`
@@ -32,5 +32,5 @@ var ge=Object.create;var P=Object.defineProperty;var de=Object.getOwnPropertyDes
32
32
  `))):l=e.stylize("[Circular]","special")),ee(i)){if(u&&o.match(/^\d+$/))return l;i=JSON.stringify(""+o),i.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(i=i.substr(1,i.length-2),i=e.stylize(i,"name")):(i=i.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),i=e.stylize(i,"string"))}return i+": "+l}r(H,"formatProperty");function qe(e,t){if(ee(t))return e.stylize("undefined","undefined");if(te(t)){let n="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(n,"string")}if(Ye(t))return e.stylize(""+t,"number");if(ke(t))return e.stylize(""+t,"boolean");if(ne(t))return e.stylize("null","null")}r(qe,"formatPrimitive");function Je(e,t,n){let s=0;return e.reduce(function(u,i){return s++,i.indexOf(`
33
33
  `)>=0&&s++,u+i.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?n[0]+(t===""?"":t+`
34
34
  `)+" "+e.join(`,
35
- `)+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}r(Je,"reduceToSingleString");var oe=r((e,...t)=>X(R,e,t),"format");var G=class{static{r(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,n){this.manager=t,this.ns=n,this.color=K(n),this.last=0,this.enabled=t.enabled.some(s=>s.test(n))}log(...t){if(!this.enabled)return;let n,s=t[0];typeof s=="function"?n=s():n=String(s);let o=Date.now()-(this.last||Date.now());n=oe(n,...t);let u=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(u),this.last=Date.now()}},$=class{static{r(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function Ke(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}r(Ke,"extract");var U;function ie(e){let t=globalThis.DEBUG;U||(U=new $(Ke(t)));let n=new G(U,e);return U.debuggers.set(e,n),Object.assign(n.log.bind(n),{self:n})}r(ie,"debug");function Xe(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let c=0;c<t.length;c++)t[c]=255;for(let c=0;c<e.length;c++){let a=e.charAt(c),g=a.charCodeAt(0);if(t[g]!==255)throw new TypeError(a+" is ambiguous");t[g]=c}let n=e.length,s=e.charAt(0),o=Math.log(n)/Math.log(256),u=Math.log(256)/Math.log(n);function i(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let a=0,g=0,d=0,_=c.length;for(;d!==_&&c[d]===0;)d++,a++;let h=(_-d)*u+1>>>0,E=new Uint8Array(h);for(;d!==_;){let f=c[d],A=0;for(let O=h-1;(f!==0||A<g)&&O!==-1;O--,A++)f+=256*E[O]>>>0,E[O]=f%n>>>0,f=f/n>>>0;if(f!==0)throw new Error("Non-zero carry");g=A,d++}let m=h-g;for(;m!==h&&E[m]===0;)m++;let S=s.repeat(a);for(;m<h;++m)S+=e.charAt(E[m]);return S}r(i,"encode");function l(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let a=0,g=0,d=0;for(;c[a]===s;)g++,a++;let _=(c.length-a)*o+1>>>0,h=new Uint8Array(_);for(;c[a];){let f=t[c.charCodeAt(a)];if(f===255)return;let A=0;for(let O=_-1;(f!==0||A<d)&&O!==-1;O--,A++)f+=n*h[O]>>>0,h[O]=f%256>>>0,f=f/256>>>0;if(f!==0)throw new Error("Non-zero carry");d=A,a++}let E=_-d;for(;E!==_&&h[E]===0;)E++;let m=new Uint8Array(g+(_-E)),S=g;for(;E!==_;)m[S++]=h[E++];return m}r(l,"decodeUnsafe");function p(c){let a=l(c);if(a)return a;throw new Error("Non-base"+n+" character")}return r(p,"decode"),{encode:i,decodeUnsafe:l,decode:p}}r(Xe,"base");var se=Xe;var Qe="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ce=se(Qe);var x=ie("zuplo:runtime:external-service");function et(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=b.instance.runtime;if(t&&t!=="undefined")try{let n=atob(t);e=JSON.parse(n)}catch{}return e}r(et,"getServiceAuth");async function le(e,t){let n=et();if(n)if(x(`Using external service auth. ClientId: ${n.clientId})`),typeof e=="string"){let s=new URL(e),o=s.hostname,u=t??{},i=new Headers(u.headers||{});i.set("CF-Access-Client-Id",n.clientId),i.set("CF-Access-Client-Secret",n.clientSecret),u.headers=i;let l;if(n.customServiceMapping&&n.customServiceMapping[o])l=`https://${n.customServiceMapping[o]}`;else if(b.instance.useLegacyServiceRouting)l=`https://${o}.zuptunnel.com`;else{x("Using sha256 service routing");let a=b.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE){let g=await tt(o,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE),d=ae(a.ENVIRONMENT_TYPE),_=await V(`${a.ACCOUNT_NAME}-${a.PROJECT_NAME}-${d}`);_==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||_==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?l=`https://${g}.zuptunnel.com`:l=`https://${g}.t.zuplo.app`}else throw x("Cannot use sha256 service routing, missing build variables"),new y("Failed to generate fully qualified tunnel url.")}let p=new URL(`${l}${s.pathname}${s.search}`);x(`Calling external service: ${p.toString()}`);let c=await I(p.toString(),u);if(c.status===403&&c.headers.get("cf-access-domain")!==null)throw C.console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:l}),new y("Could not connect to secure tunnel.");return c}else throw x("Cannot call external service with Request object"),new y("Currently, we only support fetch(<some_string>, ...).");else throw x("There is no external service auth configured for this zup."),new y("There are no external services configured for this zup.")}r(le,"externalServiceHandler");async function ue(e,t){if(typeof e=="string"){let n=new URL(e),s=n.hostname,o=t??{},u=`http://${s}.zuplo.svc.cluster.local:9000`,i=new URL(`${u}${n.pathname}${n.search}`),l=new Headers(o.headers||{});return l.set(N,s),o.headers=l,await I(i.toString(),o)}else throw new y("Currently, we only support fetch(<some_string>, ...).")}r(ue,"clusterServiceHandler");async function tt(e,t,n,s){let o=e.toLowerCase(),u=t.toLowerCase(),i=n.toLowerCase(),l=ae(s);x(`Hashing service name: ${u}-${o}.${u}-${i}-${l}`);let p=await V(`${u}-${o}`),c=await V(`${u}-${i}-${l}`);return`${p}.${c}`}r(tt,"hashServiceName");async function V(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(u=>u.toString(16).padStart(2,"0")).join("").slice(0,-1)}r(V,"hashSegment");function ae(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}r(ae,"sanitizeEnvironmentType");var k=new Map;k.set("service:",le);k.set("local:",ue);var I=globalThis.fetch;function B(e,t){let n=nt(t);if(typeof e=="string"){let s=new URL(e),o=k.get(s.protocol);return o?o(e,n):I(e,n)}else return I(e,n)}r(B,"internalFetch");globalThis.fetch=B;var nt=r(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let n=e;return n.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var rt={console:{log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),debug:console.debug.bind(console),assert:console.assert.bind(console),clear:console.clear.bind(console),count:console.count.bind(console),countReset:console.countReset.bind(console),dir:console.dir.bind(console),dirxml:console.dirxml.bind(console),group:console.group.bind(console),groupCollapsed:console.groupCollapsed.bind(console),groupEnd:console.groupEnd.bind(console),table:console.table.bind(console),time:console.time.bind(console),timeEnd:console.timeEnd.bind(console),timeLog:console.timeLog.bind(console),timeStamp:console.timeStamp.bind(console),trace:console.trace.bind(console),profile:console.profile.bind(console),profileEnd:console.profileEnd.bind(console)},fetch:B},C=rt;var Y="2025-02-06",pe=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2025-02-06":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!0,useForwardRedirectsPropOnUrlForwardHandler:!0}});function fe(){return new b({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Y,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:pe[Y]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}r(fe,"getMockEnvironment");var b=class e{static{r(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(C.console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=fe()),this.#e}constructor({build:t,runtime:n}){let s;try{if(n.ZUPLO_SYSTEM_CONFIGURATIONS){let o=new TextDecoder().decode(ce.decode(n.ZUPLO_SYSTEM_CONFIGURATIONS)),u=JSON.parse(o);for(let i of Object.keys(u))n[i]||(n[i]=u[i])}if(n.__ZUPLO_CONFIG){let o=atob(n.__ZUPLO_CONFIG);s=JSON.parse(o)}}catch(o){C.console.error("Failed to parse runtime configuration",o)}this.config=s??{},this.build=t,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get zuploEdgeApiUrl(){return this.config.zuplo_edge_api_url??"https://api.zuploedge.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.config.auth_client_id??this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.config.auth_client_secret??this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get authPublicKey(){return this.config.auth_public_key??this.runtime.__ZUPLO_AUTH_PUBLIC_KEY}get authPrivateKey(){return this.config.auth_private_key??this.runtime.__ZUPLO_AUTH_PRIVATE_KEY}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isManagedDedicated(){return this.runtime.__ZUPLO_IS_MANAGED_DEDICATED==="true"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}get rateLimitServiceTimeoutMs(){let t=this.runtime.__ZUPLO_RATE_LIMIT_TIMEOUT_MS,n=this.config.rate_limit_service_timeout_ms,s=t??n;if(!s)return 500;let o=Number(s);return Number.isFinite(o)&&o>0?o:500}};export{r as a,ot as b,it as c,st as d,ct as e,lt as f,ie as g,W as h,y as i,q as j,b as k,ft as l,me as m,Oe as n,ye as o,gt as p,dt as q,_t as r,Re as s,be as t,Ae as u,xe as v,Le as w,Et as x,ht as y,mt as z,Ot as A,yt as B,Rt as C,bt as D,At as E,xt as F,Lt as G,Te as H,Pe as I,Ie as J,Ce as K,Se as L,we as M,Ue as N,Ne as O,Tt as P,N as Q,De as R,Pt as S,It as T,Ct as U,St as V,wt as W,Ut as X,Nt as Y,C as Z};
36
- /*! For license information please see chunk-SSAQ7DDU.js.LEGAL.txt */
35
+ `)+" "+n[1]:n[0]+t+" "+e.join(", ")+" "+n[1]}r(Je,"reduceToSingleString");var oe=r((e,...t)=>X(R,e,t),"format");var G=class{static{r(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,n){this.manager=t,this.ns=n,this.color=K(n),this.last=0,this.enabled=t.enabled.some(s=>s.test(n))}log(...t){if(!this.enabled)return;let n,s=t[0];typeof s=="function"?n=s():n=String(s);let o=Date.now()-(this.last||Date.now());n=oe(n,...t);let u=`${this.color(this.ns)} ${n} ${this.color(`+${o}ms`)}`;console.log(u),this.last=Date.now()}},$=class{static{r(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function Ke(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}r(Ke,"extract");var U;function ie(e){let t=globalThis.DEBUG;U||(U=new $(Ke(t)));let n=new G(U,e);return U.debuggers.set(e,n),Object.assign(n.log.bind(n),{self:n})}r(ie,"debug");function Xe(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let c=0;c<t.length;c++)t[c]=255;for(let c=0;c<e.length;c++){let a=e.charAt(c),d=a.charCodeAt(0);if(t[d]!==255)throw new TypeError(a+" is ambiguous");t[d]=c}let n=e.length,s=e.charAt(0),o=Math.log(n)/Math.log(256),u=Math.log(256)/Math.log(n);function i(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let a=0,d=0,g=0,_=c.length;for(;g!==_&&c[g]===0;)g++,a++;let h=(_-g)*u+1>>>0,E=new Uint8Array(h);for(;g!==_;){let f=c[g],A=0;for(let O=h-1;(f!==0||A<d)&&O!==-1;O--,A++)f+=256*E[O]>>>0,E[O]=f%n>>>0,f=f/n>>>0;if(f!==0)throw new Error("Non-zero carry");d=A,g++}let m=h-d;for(;m!==h&&E[m]===0;)m++;let S=s.repeat(a);for(;m<h;++m)S+=e.charAt(E[m]);return S}r(i,"encode");function l(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let a=0,d=0,g=0;for(;c[a]===s;)d++,a++;let _=(c.length-a)*o+1>>>0,h=new Uint8Array(_);for(;c[a];){let f=t[c.charCodeAt(a)];if(f===255)return;let A=0;for(let O=_-1;(f!==0||A<g)&&O!==-1;O--,A++)f+=n*h[O]>>>0,h[O]=f%256>>>0,f=f/256>>>0;if(f!==0)throw new Error("Non-zero carry");g=A,a++}let E=_-g;for(;E!==_&&h[E]===0;)E++;let m=new Uint8Array(d+(_-E)),S=d;for(;E!==_;)m[S++]=h[E++];return m}r(l,"decodeUnsafe");function p(c){let a=l(c);if(a)return a;throw new Error("Non-base"+n+" character")}return r(p,"decode"),{encode:i,decodeUnsafe:l,decode:p}}r(Xe,"base");var se=Xe;var Qe="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ce=se(Qe);var x=ie("zuplo:runtime:external-service");function et(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=b.instance.runtime;if(t&&t!=="undefined")try{let n=atob(t);e=JSON.parse(n)}catch{}return e}r(et,"getServiceAuth");async function le(e,t){let n=et();if(n)if(x(`Using external service auth. ClientId: ${n.clientId})`),typeof e=="string"){let s=new URL(e),o=s.hostname,u=t??{},i=new Headers(u.headers||{});i.set("CF-Access-Client-Id",n.clientId),i.set("CF-Access-Client-Secret",n.clientSecret),u.headers=i;let l;if(n.customServiceMapping&&n.customServiceMapping[o])l=`https://${n.customServiceMapping[o]}`;else if(b.instance.useLegacyServiceRouting)l=`https://${o}.zuptunnel.com`;else{x("Using sha256 service routing");let a=b.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE){let d=await tt(o,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE),g=ae(a.ENVIRONMENT_TYPE),_=await V(`${a.ACCOUNT_NAME}-${a.PROJECT_NAME}-${g}`);_==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||_==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?l=`https://${d}.zuptunnel.com`:l=`https://${d}.t.zuplo.app`}else throw x("Cannot use sha256 service routing, missing build variables"),new y("Failed to generate fully qualified tunnel url.")}let p=new URL(`${l}${s.pathname}${s.search}`);x(`Calling external service: ${p.toString()}`);let c=await I(p.toString(),u);if(c.status===403&&c.headers.get("cf-access-domain")!==null)throw C.console.error("403 Forbidden when calling external service.",{clientId:n.clientId,tunnelHost:l}),new y("Could not connect to secure tunnel.");return c}else throw x("Cannot call external service with Request object"),new y("Currently, we only support fetch(<some_string>, ...).");else throw x("There is no external service auth configured for this zup."),new y("There are no external services configured for this zup.")}r(le,"externalServiceHandler");async function ue(e,t){if(typeof e=="string"){let n=new URL(e),s=n.hostname,o=t??{},u=`http://${s}.zuplo.svc.cluster.local:9000`,i=new URL(`${u}${n.pathname}${n.search}`),l=new Headers(o.headers||{});return l.set(N,s),o.headers=l,await I(i.toString(),o)}else throw new y("Currently, we only support fetch(<some_string>, ...).")}r(ue,"clusterServiceHandler");async function tt(e,t,n,s){let o=e.toLowerCase(),u=t.toLowerCase(),i=n.toLowerCase(),l=ae(s);x(`Hashing service name: ${u}-${o}.${u}-${i}-${l}`);let p=await V(`${u}-${o}`),c=await V(`${u}-${i}-${l}`);return`${p}.${c}`}r(tt,"hashServiceName");async function V(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(u=>u.toString(16).padStart(2,"0")).join("").slice(0,-1)}r(V,"hashSegment");function ae(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}r(ae,"sanitizeEnvironmentType");var k=new Map;k.set("service:",le);k.set("local:",ue);var I=globalThis.fetch;function B(e,t){let n=nt(t);if(typeof e=="string"){let s=new URL(e),o=k.get(s.protocol);return o?o(e,n):I(e,n)}else return I(e,n)}r(B,"internalFetch");globalThis.fetch=B;var nt=r(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let n=e;return n.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var rt={console:{log:console.log.bind(console),info:console.info.bind(console),warn:console.warn.bind(console),error:console.error.bind(console),debug:console.debug.bind(console),assert:console.assert.bind(console),clear:console.clear.bind(console),count:console.count.bind(console),countReset:console.countReset.bind(console),dir:console.dir.bind(console),dirxml:console.dirxml.bind(console),group:console.group.bind(console),groupCollapsed:console.groupCollapsed.bind(console),groupEnd:console.groupEnd.bind(console),table:console.table.bind(console),time:console.time.bind(console),timeEnd:console.timeEnd.bind(console),timeLog:console.timeLog.bind(console),timeStamp:console.timeStamp.bind(console),trace:console.trace.bind(console),profile:console.profile.bind(console),profileEnd:console.profileEnd.bind(console)},fetch:B},C=rt;var Y="2025-02-06",pe=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!1,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2024-09-02":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!1,useForwardRedirectsPropOnUrlForwardHandler:!1},"2025-02-06":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0,allowCustomPorts:!0,removeLegacyLogInitialization:!0,useForwardRedirectsPropOnUrlForwardHandler:!0}});function fe(){return new b({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Y,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:pe[Y]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}r(fe,"getMockEnvironment");var b=class e{static{r(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(C.console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=fe()),this.#e}constructor({build:t,runtime:n}){let s;try{if(n.ZUPLO_SYSTEM_CONFIGURATIONS){let o=new TextDecoder().decode(ce.decode(n.ZUPLO_SYSTEM_CONFIGURATIONS)),u=JSON.parse(o);for(let i of Object.keys(u))n[i]||(n[i]=u[i])}if(n.__ZUPLO_CONFIG){let o=atob(n.__ZUPLO_CONFIG);s=JSON.parse(o)}}catch(o){C.console.error("Failed to parse runtime configuration",o)}this.config=s??{},this.build=t,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get zuploEdgeApiUrl(){return this.config.zuplo_edge_api_url??"https://api.zuploedge.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuploedge.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuploedge.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuploedge.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuploedge.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.config.auth_client_id??this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.config.auth_client_secret??this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get authPublicKey(){return this.config.auth_public_key??this.runtime.__ZUPLO_AUTH_PUBLIC_KEY}get authPrivateKey(){return this.config.auth_private_key??this.runtime.__ZUPLO_AUTH_PRIVATE_KEY}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isManagedDedicated(){return this.runtime.__ZUPLO_IS_MANAGED_DEDICATED==="true"}get isDeno(){if(this.runtime.__ZUPLO_RUNTIME_TYPE)return this.runtime.__ZUPLO_RUNTIME_TYPE==="deno";if(this.config.runtime_type)return this.config.runtime_type==="deno";{let t=typeof globalThis.Deno<"u"&&globalThis.Deno.version&&globalThis.Deno.version.deno;return typeof WebSocketPair!="function"&&t}}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}get rateLimitServiceTimeoutMs(){let t=this.runtime.__ZUPLO_RATE_LIMIT_TIMEOUT_MS,n=this.config.rate_limit_service_timeout_ms,s=t??n;if(!s)return 500;let o=Number(s);return Number.isFinite(o)&&o>0?o:500}};export{r as a,ot as b,it as c,st as d,ct as e,lt as f,ie as g,W as h,y as i,q as j,b as k,ft as l,me as m,Oe as n,ye as o,dt as p,gt as q,_t as r,Re as s,be as t,Ae as u,xe as v,Le as w,Et as x,ht as y,mt as z,Ot as A,yt as B,Rt as C,bt as D,At as E,xt as F,Lt as G,Te as H,Pe as I,Ie as J,Ce as K,Se as L,we as M,Ue as N,Ne as O,Tt as P,N as Q,De as R,Pt as S,It as T,Ct as U,St as V,wt as W,Ut as X,Nt as Y,C as Z};
36
+ /*! For license information please see chunk-6JMEGIXE.js.LEGAL.txt */
@@ -22,4 +22,4 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as e,k as o}from"./chunk-SSAQ7DDU.js";var s={MCP_TOOL_USAGE:"mcp_tool_usage"};var r=class{static{e(this,"BaseAnalyticsEvent")}eventId;requestId;timestamp;accountName;projectName;deploymentName;unit;value;constructor(t){this.eventId=t.eventId,this.requestId=t.requestId,this.timestamp=t.timestamp??new Date,this.accountName=t.accountName,this.projectName=t.projectName,this.deploymentName=t.deploymentName,this.unit=t.unit,this.value=t.value}};var i=class extends r{static{e(this,"McpToolUsageEvent")}eventType=s.MCP_TOOL_USAGE;metadata;constructor(t){t.metadata.toolName.trim()||(t.metadata.toolName="unknown"),t.metadata.toolVersion.trim()||(t.metadata.toolVersion="unknown"),t.metadata.toolPath.trim()||(t.metadata.toolPath="unknown"),t.metadata.toolMethod.trim()||(t.metadata.toolMethod="unknown"),t.metadata.toolOperationId.trim()||(t.metadata.toolOperationId="unknown"),super(t),this.metadata=t.metadata}};var d={[s.MCP_TOOL_USAGE]:i};function c(a,t){let n=d[a];return new n(t)}e(c,"createAnalyticsEvent");var v=class{static{e(this,"ZuploGatewayAnalyticsContext")}#t;#e;constructor(t){this.#t=[],this.#e=t}addAnalyticsEvent(t,n,p,m){let l=this.createAnalyticsEvent(t,n,p,m);this.#t.push(l)}getAnalyticsEvents(){return this.#t}createAnalyticsEvent(t,n,p,m){return c(n,{eventId:crypto.randomUUID(),requestId:this.#e,accountName:o.instance.build.ACCOUNT_NAME??"unknown",projectName:o.instance.build.PROJECT_NAME??"unknown",deploymentName:o.instance.deploymentName??"unknown",metadata:p,unit:m,value:t})}};export{v as a};
25
+ import{a as e,k as o}from"./chunk-6JMEGIXE.js";var s={MCP_TOOL_USAGE:"mcp_tool_usage"};var r=class{static{e(this,"BaseAnalyticsEvent")}eventId;requestId;timestamp;accountName;projectName;deploymentName;unit;value;constructor(t){this.eventId=t.eventId,this.requestId=t.requestId,this.timestamp=t.timestamp??new Date,this.accountName=t.accountName,this.projectName=t.projectName,this.deploymentName=t.deploymentName,this.unit=t.unit,this.value=t.value}};var i=class extends r{static{e(this,"McpToolUsageEvent")}eventType=s.MCP_TOOL_USAGE;metadata;constructor(t){t.metadata.toolName.trim()||(t.metadata.toolName="unknown"),t.metadata.toolVersion.trim()||(t.metadata.toolVersion="unknown"),t.metadata.toolPath.trim()||(t.metadata.toolPath="unknown"),t.metadata.toolMethod.trim()||(t.metadata.toolMethod="unknown"),t.metadata.toolOperationId.trim()||(t.metadata.toolOperationId="unknown"),super(t),this.metadata=t.metadata}};var d={[s.MCP_TOOL_USAGE]:i};function c(a,t){let n=d[a];return new n(t)}e(c,"createAnalyticsEvent");var v=class{static{e(this,"ZuploGatewayAnalyticsContext")}#t;#e;constructor(t){this.#t=[],this.#e=t}addAnalyticsEvent(t,n,p,m){let l=this.createAnalyticsEvent(t,n,p,m);this.#t.push(l)}getAnalyticsEvents(){return this.#t}createAnalyticsEvent(t,n,p,m){return c(n,{eventId:crypto.randomUUID(),requestId:this.#e,accountName:o.instance.build.ACCOUNT_NAME??"unknown",projectName:o.instance.build.PROJECT_NAME??"unknown",deploymentName:o.instance.deploymentName??"unknown",metadata:p,unit:m,value:t})}};export{v as a};
@@ -22,4 +22,4 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as i,k as o}from"./chunk-SSAQ7DDU.js";var p=(n=>(n.Build="build-data",n.CorsPreflight="cors-preflight",n.DeveloperPortal="developer-portal",n.ZudokuPortal="zudoku-portal",n.DeveloperPortalLegacy="developer-portal-legacy",n.StripePlugin="stripe-plugin",n.EmptyGatewayCatchall="empty-gateway-catchall",n.Ping="ping",n.UnmatchedPath="unmatched-path",n))(p||{});var g=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function l(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!g.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):e.startsWith("ZUDOKU_")?!e.startsWith("ZUDOKU_PUBLIC_"):!1}i(l,"isRestrictedEnvVariableName");function _(e){return!!e.startsWith("ZUPLO_")}i(_,"isZuploReadableEnvVariableName");var d=new Proxy({},{get(e,t){let r=String(t);switch(r){case"ZUPLO_ENVIRONMENT_TYPE":return o.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return o.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return o.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return o.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return o.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return o.instance.build.BUILD_ID;case"ZUPLO_COMPATIBILITY_DATE":return o.instance.build.COMPATIBILITY_DATE}if(!(l(r)&&!_(r)))return o.instance.runtime[r]}});function f(e,t,r){return`_${a(`${e}_${t}_${r}`)}`}i(f,"getRawOperationDataIdentifierName");function L(e,t,r,s){return`_${a(e.toLowerCase())}_${t.toLowerCase()}_${r.toLowerCase()}_${s.toLowerCase()}`}i(L,"getIdForParameterSchema");function E(e,t,r){return`_${a(e.toLowerCase())}_${t.toLowerCase()}_rb_${a(r.toLowerCase())}`}i(E,"getIdForRequestBodySchema");function C(e,t){return`_${a(e)}_${a(t)}`}i(C,"getIdForRefSchema");function a(e){let t=e.replace(/\[/g,"_LBRACKET_").replace(/\]/g,"_RBRACKET_").replace(/\{/g,"_LCURLY_").replace(/\}/g,"_RCURLY_").replace(/\//g,"_SLASH_").replace(/-/g,"_DASH_").replace(/\./g,"_DOT_").replace(/\+/g,"_PLUS_").replace(/:/g,"_COLON_").replace(/@/g,"_AT_").replace(/\$/g,"_DOLLAR_").replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(t)||(t="_"+t),t}i(a,"sanitizedIdentifierName");export{p as a,l as b,_ as c,d,f as e,L as f,E as g,C as h,a as i};
25
+ import{a as i,k as o}from"./chunk-6JMEGIXE.js";var p=(n=>(n.Build="build-data",n.CorsPreflight="cors-preflight",n.DeveloperPortal="developer-portal",n.ZudokuPortal="zudoku-portal",n.DeveloperPortalLegacy="developer-portal-legacy",n.StripePlugin="stripe-plugin",n.EmptyGatewayCatchall="empty-gateway-catchall",n.Ping="ping",n.UnmatchedPath="unmatched-path",n))(p||{});var g=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function l(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!g.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):e.startsWith("ZUDOKU_")?!e.startsWith("ZUDOKU_PUBLIC_"):!1}i(l,"isRestrictedEnvVariableName");function _(e){return!!e.startsWith("ZUPLO_")}i(_,"isZuploReadableEnvVariableName");var d=new Proxy({},{get(e,t){let r=String(t);switch(r){case"ZUPLO_ENVIRONMENT_TYPE":return o.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return o.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return o.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return o.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return o.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return o.instance.build.BUILD_ID;case"ZUPLO_COMPATIBILITY_DATE":return o.instance.build.COMPATIBILITY_DATE}if(!(l(r)&&!_(r)))return o.instance.runtime[r]}});function f(e,t,r){return`_${a(`${e}_${t}_${r}`)}`}i(f,"getRawOperationDataIdentifierName");function L(e,t,r,s){return`_${a(e.toLowerCase())}_${t.toLowerCase()}_${r.toLowerCase()}_${s.toLowerCase()}`}i(L,"getIdForParameterSchema");function E(e,t,r){return`_${a(e.toLowerCase())}_${t.toLowerCase()}_rb_${a(r.toLowerCase())}`}i(E,"getIdForRequestBodySchema");function C(e,t){return`_${a(e)}_${a(t)}`}i(C,"getIdForRefSchema");function a(e){let t=e.replace(/\[/g,"_LBRACKET_").replace(/\]/g,"_RBRACKET_").replace(/\{/g,"_LCURLY_").replace(/\}/g,"_RCURLY_").replace(/\//g,"_SLASH_").replace(/-/g,"_DASH_").replace(/\./g,"_DOT_").replace(/\+/g,"_PLUS_").replace(/:/g,"_COLON_").replace(/@/g,"_AT_").replace(/\$/g,"_DOLLAR_").replace(/[^a-zA-Z0-9_]/g,"_");return/^[a-zA-Z_]/.test(t)||(t="_"+t),t}i(a,"sanitizedIdentifierName");export{p as a,l as b,_ as c,d,f as e,L as f,E as g,C as h,a as i};
package/out/esm/index.js CHANGED
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as Nt,d as Ne,e as Zw,f as Ws,g as Ks,h as Mw,i as qw}from"./chunk-ABYPZMH4.js";import{a as Hf}from"./chunk-7X7Y6YCS.js";import{A as Of,B as Cf,C as _o,D as ko,E as Eo,F as $o,G as To,H as Oo,I as Af,J as Nf,K as Co,L as Ao,M as Lf,N as No,O as Lo,P as zf,Q as Uf,R as Df,S as jf,T as Zf,U as Mf,V as qf,W as tn,X as rn,Y as zo,Z as B,a as i,b as ee,c as Dw,d as Pt,e as jw,f as yf,g as Me,h as fe,i as j,j as y,k as R,l as bf,m as en,n as vf,o as mr,p as wf,q as xf,r as Rf,s as Pf,t as If,u as Sf,v as _f,w as kf,x as Ef,y as $f,z as Tf}from"./chunk-SSAQ7DDU.js";var Rg=Dw(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.parse=Rx;Xo.serialize=Px;var hx=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,yx=/^[\u0021-\u003A\u003C-\u007E]*$/,bx=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,vx=/^[\u0020-\u003A\u003D-\u007E]*$/,wx=Object.prototype.toString,xx=(()=>{let t=i(function(){},"C");return t.prototype=Object.create(null),t})();function Rx(t,e){let r=new xx,n=t.length;if(n<2)return r;let o=e?.decode||Ix,s=0;do{let a=t.indexOf("=",s);if(a===-1)break;let u=t.indexOf(";",s),c=u===-1?n:u;if(a>c){s=t.lastIndexOf(";",a-1)+1;continue}let l=wg(t,s,a),d=xg(t,a,l),p=t.slice(l,d);if(r[p]===void 0){let m=wg(t,a+1,c),f=xg(t,c,m),h=o(t.slice(m,f));r[p]=h}s=c+1}while(s<n);return r}i(Rx,"parse");function wg(t,e,r){do{let n=t.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<r);return r}i(wg,"startIndex");function xg(t,e,r){for(;e>r;){let n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}i(xg,"endIndex");function Px(t,e,r){let n=r?.encode||encodeURIComponent;if(!hx.test(t))throw new TypeError(`argument name is invalid: ${t}`);let o=n(e);if(!yx.test(o))throw new TypeError(`argument val is invalid: ${e}`);let s=t+"="+o;if(!r)return s;if(r.maxAge!==void 0){if(!Number.isInteger(r.maxAge))throw new TypeError(`option maxAge is invalid: ${r.maxAge}`);s+="; Max-Age="+r.maxAge}if(r.domain){if(!bx.test(r.domain))throw new TypeError(`option domain is invalid: ${r.domain}`);s+="; Domain="+r.domain}if(r.path){if(!vx.test(r.path))throw new TypeError(`option path is invalid: ${r.path}`);s+="; Path="+r.path}if(r.expires){if(!Sx(r.expires)||!Number.isFinite(r.expires.valueOf()))throw new TypeError(`option expires is invalid: ${r.expires}`);s+="; Expires="+r.expires.toUTCString()}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.partitioned&&(s+="; Partitioned"),r.priority)switch(typeof r.priority=="string"?r.priority.toLowerCase():void 0){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${r.priority}`)}if(r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:case"strict":s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${r.sameSite}`)}return s}i(Px,"serialize");function Ix(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}i(Ix,"decode");function Sx(t){return wx.call(t)==="[object Date]"}i(Sx,"isDate")});function I(t,e,r){function n(u,c){var l;Object.defineProperty(u,"_zod",{value:u._zod??{},enumerable:!1}),(l=u._zod).traits??(l.traits=new Set),u._zod.traits.add(t),e(u,c);for(let d in a.prototype)Object.defineProperty(u,d,{value:a.prototype[d].bind(u)});u._zod.constr=a,u._zod.def=c}i(n,"init");let o=r?.Parent??Object;class s extends o{static{i(this,"Definition")}}Object.defineProperty(s,"name",{value:t});function a(u){var c;let l=r?.Parent?new s:this;n(l,u),(c=l._zod).deferred??(c.deferred=[]);for(let d of l._zod.deferred)d();return l}return i(a,"_"),Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i(u=>r?.Parent&&u instanceof r.Parent?!0:u?._zod?.traits?.has(t),"value")}),Object.defineProperty(a,"name",{value:t}),a}function Ae(t){return t&&Object.assign(Pn,t),Pn}var li,yt,Pn,Sr=ee(()=>{i(I,"$constructor");li=Symbol("zod_brand"),yt=class extends Error{static{i(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Pn={};i(Ae,"config")});var Y={};Pt(Y,{BIGINT_FORMAT_RANGES:()=>nu,Class:()=>Wa,NUMBER_FORMAT_RANGES:()=>ru,aborted:()=>tr,allowsEval:()=>Ya,assert:()=>_R,assertEqual:()=>RR,assertIs:()=>IR,assertNever:()=>SR,assertNotEqual:()=>PR,assignProp:()=>Xa,cached:()=>Sn,cleanEnum:()=>jR,cleanRegex:()=>_n,clone:()=>Ke,createTransparentProxy:()=>CR,defineLazy:()=>we,esc:()=>er,escapeRegex:()=>bt,extend:()=>LR,finalizeIssue:()=>Qe,floatSafeRemainder:()=>Qa,getElementAtPath:()=>ER,getLengthableOrigin:()=>Tn,getParsedType:()=>OR,getSizableOrigin:()=>$n,getValidEnumValues:()=>kR,isObject:()=>pi,isPlainObject:()=>kn,issue:()=>ou,joinValues:()=>D,jsonStringifyReplacer:()=>Ka,merge:()=>zR,normalizeParams:()=>J,nullish:()=>Mt,numKeys:()=>TR,omit:()=>NR,optionalKeys:()=>tu,partial:()=>UR,pick:()=>AR,prefixIssues:()=>qe,primitiveTypes:()=>eu,promiseAllObject:()=>$R,propertyKeyTypes:()=>En,randomString:()=>di,required:()=>DR,stringifyPrimitive:()=>te,unwrapMessage:()=>In});function RR(t){return t}function PR(t){return t}function IR(t){}function SR(t){throw new Error}function _R(t){}function kR(t){let e=Object.keys(t).filter(n=>typeof t[t[n]]!="number"),r={};for(let n of e)r[n]=t[n];return Object.values(r)}function D(t,e="|"){return t.map(r=>te(r)).join(e)}function Ka(t,e){return typeof e=="bigint"?e.toString():e}function Sn(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Mt(t){return t==null}function _n(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Qa(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return s%a/10**o}function we(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Xa(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ER(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function $R(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function di(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function er(t){return JSON.stringify(t)}function pi(t){return typeof t=="object"&&t!==null}function kn(t){return typeof t=="object"&&t!==null&&Object.getPrototypeOf(t)===Object.prototype}function TR(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function bt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ke(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function J(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:i(()=>e,"error")};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:i(()=>e.error,"error")}:e}function CR(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function te(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function tu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional")}function AR(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Ke(t,{...t._zod.def,shape:r,checks:[]})}function NR(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Ke(t,{...t._zod.def,shape:r,checks:[]})}function LR(t,e){let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Xa(this,"shape",n),n},checks:[]};return Ke(t,r)}function zR(t,e){return Ke(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Xa(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function UR(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return Ke(e,{...e._zod.def,shape:o,checks:[]})}function DR(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return Ke(e,{...e._zod.def,shape:o,checks:[]})}function tr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r].continue!==!0)return!0;return!1}function qe(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function In(t){return typeof t=="string"?t:t?.message}function Qe(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=In(t.inst?._zod.def?.error?.(t))??In(e?.error?.(t))??In(r.customError?.(t))??In(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function $n(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Tn(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function ou(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function jR(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ya,OR,En,eu,ru,nu,Wa,de=ee(()=>{i(RR,"assertEqual");i(PR,"assertNotEqual");i(IR,"assertIs");i(SR,"assertNever");i(_R,"assert");i(kR,"getValidEnumValues");i(D,"joinValues");i(Ka,"jsonStringifyReplacer");i(Sn,"cached");i(Mt,"nullish");i(_n,"cleanRegex");i(Qa,"floatSafeRemainder");i(we,"defineLazy");i(Xa,"assignProp");i(ER,"getElementAtPath");i($R,"promiseAllObject");i(di,"randomString");i(er,"esc");i(pi,"isObject");Ya=Sn(()=>{try{let t=Function;return new t(""),!0}catch{return!1}});i(kn,"isPlainObject");i(TR,"numKeys");OR=i(t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},"getParsedType"),En=new Set(["string","number","symbol"]),eu=new Set(["string","number","bigint","boolean","symbol","undefined"]);i(bt,"escapeRegex");i(Ke,"clone");i(J,"normalizeParams");i(CR,"createTransparentProxy");i(te,"stringifyPrimitive");i(tu,"optionalKeys");ru={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},nu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};i(AR,"pick");i(NR,"omit");i(LR,"extend");i(zR,"merge");i(UR,"partial");i(DR,"required");i(tr,"aborted");i(qe,"prefixIssues");i(In,"unwrapMessage");i(Qe,"finalizeIssue");i($n,"getSizableOrigin");i(Tn,"getLengthableOrigin");i(ou,"issue");i(jR,"cleanEnum");Wa=class{static{i(this,"Class")}constructor(...e){}}});function Cn(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function An(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=i(s=>{for(let a of s.issues)if(a.code==="invalid_union")a.errors.map(u=>o({issues:u}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let u=n,c=0;for(;c<a.path.length;){let l=a.path[c];c===a.path.length-1?(u[l]=u[l]||{_errors:[]},u[l]._errors.push(r(a))):u[l]=u[l]||{_errors:[]},u=u[l],c++}}},"processError");return o(t),n}function iu(t,e){let r=e||function(s){return s.message},n={errors:[]},o=i((s,a=[])=>{var u,c;for(let l of s.issues)if(l.code==="invalid_union")l.errors.map(d=>o({issues:d},l.path));else if(l.code==="invalid_key")o({issues:l.issues},l.path);else if(l.code==="invalid_element")o({issues:l.issues},l.path);else{let d=[...a,...l.path];if(d.length===0){n.errors.push(r(l));continue}let p=n,m=0;for(;m<d.length;){let f=d[m],h=m===d.length-1;typeof f=="string"?(p.properties??(p.properties={}),(u=p.properties)[f]??(u[f]={errors:[]}),p=p.properties[f]):(p.items??(p.items=[]),(c=p.items)[f]??(c[f]={errors:[]}),p=p.items[f]),h&&p.errors.push(r(l)),m++}}},"processError");return o(t),n}function eh(t){let e=[];for(let r of t)typeof r=="number"?e.push(`[${r}]`):typeof r=="symbol"?e.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?e.push(`[${JSON.stringify(r)}]`):(e.length&&e.push("."),e.push(r));return e.join("")}function su(t){let e=[],r=[...t.issues].sort((n,o)=>n.path.length-o.path.length);for(let n of r)e.push(`\u2716 ${n.message}`),n.path?.length&&e.push(` \u2192 at ${eh(n.path)}`);return e.join(`
25
+ import{a as Nt,d as Ne,e as Zw,f as Ws,g as Ks,h as Mw,i as qw}from"./chunk-ZI6BEEZC.js";import{a as Hf}from"./chunk-XGTJ3NUE.js";import{A as Of,B as Cf,C as _o,D as ko,E as Eo,F as $o,G as To,H as Oo,I as Af,J as Nf,K as Co,L as Ao,M as Lf,N as No,O as Lo,P as zf,Q as Uf,R as Df,S as jf,T as Zf,U as Mf,V as qf,W as tn,X as rn,Y as zo,Z as B,a as i,b as ee,c as Dw,d as Pt,e as jw,f as yf,g as Me,h as fe,i as j,j as y,k as R,l as bf,m as en,n as vf,o as mr,p as wf,q as xf,r as Rf,s as Pf,t as If,u as Sf,v as _f,w as kf,x as Ef,y as $f,z as Tf}from"./chunk-6JMEGIXE.js";var Rg=Dw(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.parse=Rx;Xo.serialize=Px;var hx=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,yx=/^[\u0021-\u003A\u003C-\u007E]*$/,bx=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,vx=/^[\u0020-\u003A\u003D-\u007E]*$/,wx=Object.prototype.toString,xx=(()=>{let t=i(function(){},"C");return t.prototype=Object.create(null),t})();function Rx(t,e){let r=new xx,n=t.length;if(n<2)return r;let o=e?.decode||Ix,s=0;do{let a=t.indexOf("=",s);if(a===-1)break;let u=t.indexOf(";",s),c=u===-1?n:u;if(a>c){s=t.lastIndexOf(";",a-1)+1;continue}let l=wg(t,s,a),d=xg(t,a,l),p=t.slice(l,d);if(r[p]===void 0){let m=wg(t,a+1,c),f=xg(t,c,m),h=o(t.slice(m,f));r[p]=h}s=c+1}while(s<n);return r}i(Rx,"parse");function wg(t,e,r){do{let n=t.charCodeAt(e);if(n!==32&&n!==9)return e}while(++e<r);return r}i(wg,"startIndex");function xg(t,e,r){for(;e>r;){let n=t.charCodeAt(--e);if(n!==32&&n!==9)return e+1}return r}i(xg,"endIndex");function Px(t,e,r){let n=r?.encode||encodeURIComponent;if(!hx.test(t))throw new TypeError(`argument name is invalid: ${t}`);let o=n(e);if(!yx.test(o))throw new TypeError(`argument val is invalid: ${e}`);let s=t+"="+o;if(!r)return s;if(r.maxAge!==void 0){if(!Number.isInteger(r.maxAge))throw new TypeError(`option maxAge is invalid: ${r.maxAge}`);s+="; Max-Age="+r.maxAge}if(r.domain){if(!bx.test(r.domain))throw new TypeError(`option domain is invalid: ${r.domain}`);s+="; Domain="+r.domain}if(r.path){if(!vx.test(r.path))throw new TypeError(`option path is invalid: ${r.path}`);s+="; Path="+r.path}if(r.expires){if(!Sx(r.expires)||!Number.isFinite(r.expires.valueOf()))throw new TypeError(`option expires is invalid: ${r.expires}`);s+="; Expires="+r.expires.toUTCString()}if(r.httpOnly&&(s+="; HttpOnly"),r.secure&&(s+="; Secure"),r.partitioned&&(s+="; Partitioned"),r.priority)switch(typeof r.priority=="string"?r.priority.toLowerCase():void 0){case"low":s+="; Priority=Low";break;case"medium":s+="; Priority=Medium";break;case"high":s+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${r.priority}`)}if(r.sameSite)switch(typeof r.sameSite=="string"?r.sameSite.toLowerCase():r.sameSite){case!0:case"strict":s+="; SameSite=Strict";break;case"lax":s+="; SameSite=Lax";break;case"none":s+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${r.sameSite}`)}return s}i(Px,"serialize");function Ix(t){if(t.indexOf("%")===-1)return t;try{return decodeURIComponent(t)}catch{return t}}i(Ix,"decode");function Sx(t){return wx.call(t)==="[object Date]"}i(Sx,"isDate")});function I(t,e,r){function n(u,c){var l;Object.defineProperty(u,"_zod",{value:u._zod??{},enumerable:!1}),(l=u._zod).traits??(l.traits=new Set),u._zod.traits.add(t),e(u,c);for(let d in a.prototype)Object.defineProperty(u,d,{value:a.prototype[d].bind(u)});u._zod.constr=a,u._zod.def=c}i(n,"init");let o=r?.Parent??Object;class s extends o{static{i(this,"Definition")}}Object.defineProperty(s,"name",{value:t});function a(u){var c;let l=r?.Parent?new s:this;n(l,u),(c=l._zod).deferred??(c.deferred=[]);for(let d of l._zod.deferred)d();return l}return i(a,"_"),Object.defineProperty(a,"init",{value:n}),Object.defineProperty(a,Symbol.hasInstance,{value:i(u=>r?.Parent&&u instanceof r.Parent?!0:u?._zod?.traits?.has(t),"value")}),Object.defineProperty(a,"name",{value:t}),a}function Ae(t){return t&&Object.assign(Pn,t),Pn}var li,yt,Pn,Sr=ee(()=>{i(I,"$constructor");li=Symbol("zod_brand"),yt=class extends Error{static{i(this,"$ZodAsyncError")}constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},Pn={};i(Ae,"config")});var Y={};Pt(Y,{BIGINT_FORMAT_RANGES:()=>nu,Class:()=>Wa,NUMBER_FORMAT_RANGES:()=>ru,aborted:()=>tr,allowsEval:()=>Ya,assert:()=>_R,assertEqual:()=>RR,assertIs:()=>IR,assertNever:()=>SR,assertNotEqual:()=>PR,assignProp:()=>Xa,cached:()=>Sn,cleanEnum:()=>jR,cleanRegex:()=>_n,clone:()=>Ke,createTransparentProxy:()=>CR,defineLazy:()=>we,esc:()=>er,escapeRegex:()=>bt,extend:()=>LR,finalizeIssue:()=>Qe,floatSafeRemainder:()=>Qa,getElementAtPath:()=>ER,getLengthableOrigin:()=>Tn,getParsedType:()=>OR,getSizableOrigin:()=>$n,getValidEnumValues:()=>kR,isObject:()=>pi,isPlainObject:()=>kn,issue:()=>ou,joinValues:()=>D,jsonStringifyReplacer:()=>Ka,merge:()=>zR,normalizeParams:()=>J,nullish:()=>Mt,numKeys:()=>TR,omit:()=>NR,optionalKeys:()=>tu,partial:()=>UR,pick:()=>AR,prefixIssues:()=>qe,primitiveTypes:()=>eu,promiseAllObject:()=>$R,propertyKeyTypes:()=>En,randomString:()=>di,required:()=>DR,stringifyPrimitive:()=>te,unwrapMessage:()=>In});function RR(t){return t}function PR(t){return t}function IR(t){}function SR(t){throw new Error}function _R(t){}function kR(t){let e=Object.keys(t).filter(n=>typeof t[t[n]]!="number"),r={};for(let n of e)r[n]=t[n];return Object.values(r)}function D(t,e="|"){return t.map(r=>te(r)).join(e)}function Ka(t,e){return typeof e=="bigint"?e.toString():e}function Sn(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Mt(t){return t==null}function _n(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Qa(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),a=Number.parseInt(e.toFixed(o).replace(".",""));return s%a/10**o}function we(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function Xa(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function ER(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function $R(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function di(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function er(t){return JSON.stringify(t)}function pi(t){return typeof t=="object"&&t!==null}function kn(t){return typeof t=="object"&&t!==null&&Object.getPrototypeOf(t)===Object.prototype}function TR(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function bt(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ke(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function J(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:i(()=>e,"error")};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:i(()=>e.error,"error")}:e}function CR(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function te(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function tu(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional")}function AR(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return Ke(t,{...t._zod.def,shape:r,checks:[]})}function NR(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return Ke(t,{...t._zod.def,shape:r,checks:[]})}function LR(t,e){let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Xa(this,"shape",n),n},checks:[]};return Ke(t,r)}function zR(t,e){return Ke(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Xa(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function UR(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return Ke(e,{...e._zod.def,shape:o,checks:[]})}function DR(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return Ke(e,{...e._zod.def,shape:o,checks:[]})}function tr(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r].continue!==!0)return!0;return!1}function qe(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function In(t){return typeof t=="string"?t:t?.message}function Qe(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=In(t.inst?._zod.def?.error?.(t))??In(e?.error?.(t))??In(r.customError?.(t))??In(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function $n(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Tn(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function ou(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function jR(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var Ya,OR,En,eu,ru,nu,Wa,de=ee(()=>{i(RR,"assertEqual");i(PR,"assertNotEqual");i(IR,"assertIs");i(SR,"assertNever");i(_R,"assert");i(kR,"getValidEnumValues");i(D,"joinValues");i(Ka,"jsonStringifyReplacer");i(Sn,"cached");i(Mt,"nullish");i(_n,"cleanRegex");i(Qa,"floatSafeRemainder");i(we,"defineLazy");i(Xa,"assignProp");i(ER,"getElementAtPath");i($R,"promiseAllObject");i(di,"randomString");i(er,"esc");i(pi,"isObject");Ya=Sn(()=>{try{let t=Function;return new t(""),!0}catch{return!1}});i(kn,"isPlainObject");i(TR,"numKeys");OR=i(t=>{let e=typeof t;switch(e){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(t)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":return Array.isArray(t)?"array":t===null?"null":t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?"promise":typeof Map<"u"&&t instanceof Map?"map":typeof Set<"u"&&t instanceof Set?"set":typeof Date<"u"&&t instanceof Date?"date":typeof File<"u"&&t instanceof File?"file":"object";default:throw new Error(`Unknown data type: ${e}`)}},"getParsedType"),En=new Set(["string","number","symbol"]),eu=new Set(["string","number","bigint","boolean","symbol","undefined"]);i(bt,"escapeRegex");i(Ke,"clone");i(J,"normalizeParams");i(CR,"createTransparentProxy");i(te,"stringifyPrimitive");i(tu,"optionalKeys");ru={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},nu={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};i(AR,"pick");i(NR,"omit");i(LR,"extend");i(zR,"merge");i(UR,"partial");i(DR,"required");i(tr,"aborted");i(qe,"prefixIssues");i(In,"unwrapMessage");i(Qe,"finalizeIssue");i($n,"getSizableOrigin");i(Tn,"getLengthableOrigin");i(ou,"issue");i(jR,"cleanEnum");Wa=class{static{i(this,"Class")}constructor(...e){}}});function Cn(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function An(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=i(s=>{for(let a of s.issues)if(a.code==="invalid_union")a.errors.map(u=>o({issues:u}));else if(a.code==="invalid_key")o({issues:a.issues});else if(a.code==="invalid_element")o({issues:a.issues});else if(a.path.length===0)n._errors.push(r(a));else{let u=n,c=0;for(;c<a.path.length;){let l=a.path[c];c===a.path.length-1?(u[l]=u[l]||{_errors:[]},u[l]._errors.push(r(a))):u[l]=u[l]||{_errors:[]},u=u[l],c++}}},"processError");return o(t),n}function iu(t,e){let r=e||function(s){return s.message},n={errors:[]},o=i((s,a=[])=>{var u,c;for(let l of s.issues)if(l.code==="invalid_union")l.errors.map(d=>o({issues:d},l.path));else if(l.code==="invalid_key")o({issues:l.issues},l.path);else if(l.code==="invalid_element")o({issues:l.issues},l.path);else{let d=[...a,...l.path];if(d.length===0){n.errors.push(r(l));continue}let p=n,m=0;for(;m<d.length;){let f=d[m],h=m===d.length-1;typeof f=="string"?(p.properties??(p.properties={}),(u=p.properties)[f]??(u[f]={errors:[]}),p=p.properties[f]):(p.items??(p.items=[]),(c=p.items)[f]??(c[f]={errors:[]}),p=p.items[f]),h&&p.errors.push(r(l)),m++}}},"processError");return o(t),n}function eh(t){let e=[];for(let r of t)typeof r=="number"?e.push(`[${r}]`):typeof r=="symbol"?e.push(`[${JSON.stringify(String(r))}]`):/[^\w$]/.test(r)?e.push(`[${JSON.stringify(r)}]`):(e.length&&e.push("."),e.push(r));return e.join("")}function su(t){let e=[],r=[...t.issues].sort((n,o)=>n.path.length-o.path.length);for(let n of r)e.push(`\u2716 ${n.message}`),n.path?.length&&e.push(` \u2192 at ${eh(n.path)}`);return e.join(`
26
26
  `)}var Yg,On,_r,au=ee(()=>{Sr();de();Yg=i((t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),Object.defineProperty(t,"message",{get(){return JSON.stringify(e,Ka,2)},enumerable:!0})},"initializer"),On=I("$ZodError",Yg),_r=I("$ZodError",Yg,{Parent:Error});i(Cn,"flattenError");i(An,"formatError");i(iu,"treeifyError");i(eh,"toDotPath");i(su,"prettifyError")});var mi,fi,gi,hi,yi,uu,bi,cu,vi=ee(()=>{Sr();au();de();mi=i(t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},a=e._zod.run({value:r,issues:[]},s);if(a instanceof Promise)throw new yt;if(a.issues.length){let u=new(o?.Err??t)(a.issues.map(c=>Qe(c,s,Ae())));throw Error.captureStackTrace(u,o?.callee),u}return a.value},"_parse"),fi=mi(_r),gi=i(t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},a=e._zod.run({value:r,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){let u=new(o?.Err??t)(a.issues.map(c=>Qe(c,s,Ae())));throw Error.captureStackTrace(u,o?.callee),u}return a.value},"_parseAsync"),hi=gi(_r),yi=i(t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new yt;return s.issues.length?{success:!1,error:new(t??On)(s.issues.map(a=>Qe(a,o,Ae())))}:{success:!0,data:s.value}},"_safeParse"),uu=yi(_r),bi=i(t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(a=>Qe(a,o,Ae())))}:{success:!0,data:s.value}},"_safeParseAsync"),cu=bi(_r)});var nr={};Pt(nr,{_emoji:()=>th,base64:()=>Ru,base64url:()=>Ri,bigint:()=>Eu,boolean:()=>Ou,browserEmail:()=>JR,cidrv4:()=>wu,cidrv6:()=>xu,cuid:()=>lu,cuid2:()=>du,date:()=>Iu,datetime:()=>_u,duration:()=>hu,e164:()=>Pu,email:()=>bu,emoji:()=>vu,extendedDuration:()=>MR,guid:()=>yu,hostname:()=>Nn,html5Email:()=>BR,integer:()=>$u,ip:()=>WR,ipv4:()=>wi,ipv6:()=>xi,ksuid:()=>fu,lowercase:()=>Nu,nanoid:()=>gu,null:()=>Cu,number:()=>Tu,rfc5322Email:()=>VR,string:()=>ku,time:()=>Su,ulid:()=>pu,undefined:()=>Au,unicodeEmail:()=>GR,uppercase:()=>Lu,uuid:()=>rr,uuid4:()=>qR,uuid6:()=>HR,uuid7:()=>FR,xid:()=>mu});function vu(){return new RegExp(th,"u")}function nh(t){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Su(t){return new RegExp(`^${nh(t)}$`)}function _u(t){let e=`${rh}T${nh(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}var lu,du,pu,mu,fu,gu,hu,MR,yu,rr,qR,HR,FR,bu,BR,VR,GR,JR,th,wi,xi,wu,xu,WR,Ru,Ri,Nn,Pu,rh,Iu,ku,Eu,$u,Tu,Ou,Cu,Au,Nu,Lu,Pi=ee(()=>{lu=/^[cC][^\s-]{8,}$/,du=/^[0-9a-z]+$/,pu=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,mu=/^[0-9a-vA-V]{20}$/,fu=/^[A-Za-z0-9]{27}$/,gu=/^[a-zA-Z0-9_-]{21}$/,hu=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,MR=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,yu=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,rr=i(t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,"uuid"),qR=rr(4),HR=rr(6),FR=rr(7),bu=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,BR=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,VR=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,GR=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,JR=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,th="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";i(vu,"emoji");wi=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,xi=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})$/,wu=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,xu=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,WR=new RegExp(`(${wi.source})|(${xi.source})`),Ru=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ri=/^[A-Za-z0-9_-]*$/,Nn=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Pu=/^\+(?:[0-9]){6,14}[0-9]$/,rh="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Iu=new RegExp(`^${rh}$`);i(nh,"timeSource");i(Su,"time");i(_u,"datetime");ku=i(t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},"string"),Eu=/^\d+n?$/,$u=/^\d+$/,Tu=/^-?\d+(?:\.\d+)?/i,Ou=/true|false/i,Cu=/null/i,Au=/undefined/i,Nu=/^[^A-Z]*$/,Lu=/^[^a-z]*$/});function oh(t,e,r){t.issues.length&&e.issues.push(...qe(r,t.issues))}var Ee,ih,Ii,Si,zu,Uu,Du,ju,Zu,Mu,qu,Hu,Fu,kr,Bu,Vu,Gu,Ju,Wu,Ku,Qu,Xu,Yu,_i=ee(()=>{Sr();Pi();de();Ee=I("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),ih={number:"number",bigint:"bigint",object:"date"},Ii=I("$ZodCheckLessThan",(t,e)=>{Ee.init(t,e);let r=ih[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),Si=I("$ZodCheckGreaterThan",(t,e)=>{Ee.init(t,e);let r=ih[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),zu=I("$ZodCheckMultipleOf",(t,e)=>{Ee.init(t,e),t._zod.onattach.push(r=>{var n;(n=r._zod.bag).multipleOf??(n.multipleOf=e.value)}),t._zod.check=r=>{if(typeof r.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof r.value=="bigint"?r.value%e.value===BigInt(0):Qa(r.value,e.value)===0)||r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:e.value,input:r.value,inst:t,continue:!e.abort})}}),Uu=I("$ZodCheckNumberFormat",(t,e)=>{Ee.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=ru[e.format];t._zod.onattach.push(a=>{let u=a._zod.bag;u.format=e.format,u.minimum=o,u.maximum=s,r&&(u.pattern=$u)}),t._zod.check=a=>{let u=a.value;if(r){if(!Number.isInteger(u)){a.issues.push({expected:n,format:e.format,code:"invalid_type",input:u,inst:t});return}if(!Number.isSafeInteger(u)){u>0?a.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):a.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}u<o&&a.issues.push({origin:"number",input:u,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),u>s&&a.issues.push({origin:"number",input:u,code:"too_big",maximum:s,inst:t})}}),Du=I("$ZodCheckBigIntFormat",(t,e)=>{Ee.init(t,e);let[r,n]=nu[e.format];t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,s.minimum=r,s.maximum=n}),t._zod.check=o=>{let s=o.value;s<r&&o.issues.push({origin:"bigint",input:s,code:"too_small",minimum:r,inclusive:!0,inst:t,continue:!e.abort}),s>n&&o.issues.push({origin:"bigint",input:s,code:"too_big",maximum:n,inst:t})}}),ju=I("$ZodCheckMaxSize",(t,e)=>{Ee.init(t,e),t._zod.when=r=>{let n=r.value;return!Mt(n)&&n.size!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let n=r.value;n.size<=e.maximum||r.issues.push({origin:$n(n),code:"too_big",maximum:e.maximum,input:n,inst:t,continue:!e.abort})}}),Zu=I("$ZodCheckMinSize",(t,e)=>{Ee.init(t,e),t._zod.when=r=>{let n=r.value;return!Mt(n)&&n.size!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let n=r.value;n.size>=e.minimum||r.issues.push({origin:$n(n),code:"too_small",minimum:e.minimum,input:n,inst:t,continue:!e.abort})}}),Mu=I("$ZodCheckSizeEquals",(t,e)=>{Ee.init(t,e),t._zod.when=r=>{let n=r.value;return!Mt(n)&&n.size!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag;n.minimum=e.size,n.maximum=e.size,n.size=e.size}),t._zod.check=r=>{let n=r.value,o=n.size;if(o===e.size)return;let s=o>e.size;r.issues.push({origin:$n(n),...s?{code:"too_big",maximum:e.size}:{code:"too_small",minimum:e.size},input:r.value,inst:t,continue:!e.abort})}}),qu=I("$ZodCheckMaxLength",(t,e)=>{Ee.init(t,e),t._zod.when=r=>{let n=r.value;return!Mt(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<n&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{let n=r.value;if(n.length<=e.maximum)return;let s=Tn(n);r.issues.push({origin:s,code:"too_big",maximum:e.maximum,input:n,inst:t,continue:!e.abort})}}),Hu=I("$ZodCheckMinLength",(t,e)=>{Ee.init(t,e),t._zod.when=r=>{let n=r.value;return!Mt(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>n&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{let n=r.value;if(n.length>=e.minimum)return;let s=Tn(n);r.issues.push({origin:s,code:"too_small",minimum:e.minimum,input:n,inst:t,continue:!e.abort})}}),Fu=I("$ZodCheckLengthEquals",(t,e)=>{Ee.init(t,e),t._zod.when=r=>{let n=r.value;return!Mt(n)&&n.length!==void 0},t._zod.onattach.push(r=>{let n=r._zod.bag;n.minimum=e.length,n.maximum=e.length,n.length=e.length}),t._zod.check=r=>{let n=r.value,o=n.length;if(o===e.length)return;let s=Tn(n),a=o>e.length;r.issues.push({origin:s,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},input:r.value,inst:t,continue:!e.abort})}}),kr=I("$ZodCheckStringFormat",(t,e)=>{var r;Ee.init(t,e),t._zod.onattach.push(n=>{n._zod.bag.format=e.format,e.pattern&&(n._zod.bag.pattern=e.pattern)}),(r=t._zod).check??(r.check=n=>{if(!e.pattern)throw new Error("Not implemented.");e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:e.format,input:n.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})})}),Bu=I("$ZodCheckRegex",(t,e)=>{kr.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Vu=I("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Nu),kr.init(t,e)}),Gu=I("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Lu),kr.init(t,e)}),Ju=I("$ZodCheckIncludes",(t,e)=>{Ee.init(t,e);let r=new RegExp(bt(e.includes));e.pattern=r,t._zod.onattach.push(n=>{n._zod.bag.pattern=r}),t._zod.check=n=>{n.value.includes(e.includes,e.position)||n.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:n.value,inst:t,continue:!e.abort})}}),Wu=I("$ZodCheckStartsWith",(t,e)=>{Ee.init(t,e);let r=new RegExp(`^${bt(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{n._zod.bag.pattern=r}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),Ku=I("$ZodCheckEndsWith",(t,e)=>{Ee.init(t,e);let r=new RegExp(`.*${bt(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{n._zod.bag.pattern=new RegExp(`.*${bt(e.suffix)}$`)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}});i(oh,"handleCheckPropertyResult");Qu=I("$ZodCheckProperty",(t,e)=>{Ee.init(t,e),t._zod.check=r=>{let n=e.schema._zod.run({value:r.value[e.property],issues:[]},{});if(n instanceof Promise)return n.then(o=>oh(o,r,e.property));oh(n,r,e.property)}}),Xu=I("$ZodCheckMimeType",(t,e)=>{Ee.init(t,e);let r=new Set(e.mime);t._zod.onattach.push(n=>{n._zod.bag.mime=e.mime}),t._zod.check=n=>{r.has(n.value.type)||n.issues.push({code:"invalid_value",values:e.mime,input:n.value.type,path:["type"],inst:t})}}),Yu=I("$ZodCheckOverwrite",(t,e)=>{Ee.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var Ln,ec=ee(()=>{Ln=class{static{i(this,"Doc")}constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
27
27
  `).filter(a=>a),o=Math.min(...n.map(a=>a.length-a.trimStart().length)),s=n.map(a=>a.slice(o)).map(a=>" ".repeat(this.indent*2)+a);for(let a of s)this.content.push(a)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
28
28
  `))}}});var tc,rc=ee(()=>{tc={major:4,minor:0,patch:0}});function Pc(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function bh(t){if(!Ri.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Pc(r)}function vh(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r,o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function ah(t,e,r){t.issues.length&&e.issues.push(...qe(r,t.issues)),e.value[r]=t.value}function ki(t,e,r){t.issues.length&&e.issues.push(...qe(r,t.issues)),e.value[r]=t.value}function uh(t,e,r,n){t.issues.length?n[r]===void 0?r in n?e.value[r]=void 0:e.value[r]=t.value:e.issues.push(...qe(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function ch(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>Qe(s,n,Ae())))}),e}function wh(t,e,r){let n=!0,o=t?.[e];if(r.values.size&&!r.values.has(o)&&(n=!1),r.maps.length>0)for(let s of r.maps)KR(o,s)||(n=!1);return n}function KR(t,e){let r=!0;for(let[n,o]of e)wh(t,n,o)||(r=!1);return r}function nc(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(kn(t)&&kn(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let a=nc(t[s],e[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};o[s]=a.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],a=nc(o,s);if(!a.valid)return{valid:!1,mergeErrorPath:[n,...a.mergeErrorPath]};r.push(a.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function lh(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),tr(t))return t;let n=nc(e.value,r.value);if(!n.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(n.mergeErrorPath)}`);return t.value=n.data,t}function Ei(t,e,r){t.issues.length&&e.issues.push(...qe(r,t.issues)),e.value[r]=t.value}function dh(t,e,r,n,o,s,a){t.issues.length&&(En.has(typeof n)?r.issues.push(...qe(n,t.issues)):r.issues.push({origin:"map",code:"invalid_key",input:o,inst:s,issues:t.issues.map(u=>Qe(u,a,Ae()))})),e.issues.length&&(En.has(typeof n)?r.issues.push(...qe(n,e.issues)):r.issues.push({origin:"map",code:"invalid_element",input:o,inst:s,key:n,issues:e.issues.map(u=>Qe(u,a,Ae()))})),r.value.set(t.value,e.value)}function ph(t,e){t.issues.length&&e.issues.push(...t.issues),e.value.add(t.value)}function mh(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function fh(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}function gh(t,e,r){return tr(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function hh(t){return t.value=Object.freeze(t.value),t}function yh(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(ou(o))}}var ae,zn,Ie,oc,ic,sc,ac,uc,cc,lc,dc,pc,mc,fc,gc,hc,yc,bc,vc,wc,xc,Rc,Ic,Sc,_c,kc,$i,Ec,Un,Ti,$c,Tc,Oc,Cc,Ac,Dn,Nc,Lc,zc,Uc,Dc,Oi,jc,Zc,or,Mc,qc,Hc,Fc,Bc,Vc,Gc,Jc,Wc,Kc,Qc,Xc,Yc,el,tl,jn,rl,nl,ol,il,sl,Zn=ee(()=>{_i();Sr();ec();vi();Pi();de();rc();de();ae=I("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.id=e.type+"_"+di(10),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=tc;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=i((s,a,u)=>{let c=tr(s),l;for(let d of a){if(d._zod.when){if(!d._zod.when(s))continue}else if(c)continue;let p=s.issues.length,m=d._zod.check(s);if(m instanceof Promise&&u?.async===!1)throw new yt;if(l||m instanceof Promise)l=(l??Promise.resolve()).then(async()=>{await m,s.issues.length!==p&&(c||(c=tr(s,p)))});else{if(s.issues.length===p)continue;c||(c=tr(s,p))}}return l?l.then(()=>s):s},"runChecks");t._zod.run=(s,a)=>{let u=t._zod.parse(s,a);if(u instanceof Promise){if(a.async===!1)throw new yt;return u.then(c=>o(c,n,a))}return o(u,n,a)}}t["~standard"]={validate:i(o=>{try{let s=uu(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return cu(t,o).then(a=>a.success?{value:a.data}:{issues:a.error?.issues})}},"validate"),vendor:"zod",version:1}}),zn=I("$ZodString",(t,e)=>{ae.init(t,e),t._zod.pattern=t?._zod.bag?.pattern??ku(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Ie=I("$ZodStringFormat",(t,e)=>{kr.init(t,e),zn.init(t,e)}),oc=I("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=yu),Ie.init(t,e)}),ic=I("$ZodUUID",(t,e)=>{if(e.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(n===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=rr(n))}else e.pattern??(e.pattern=rr());Ie.init(t,e)}),sc=I("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=bu),Ie.init(t,e)}),ac=I("$ZodURL",(t,e)=>{Ie.init(t,e),t._zod.check=r=>{try{let n=new URL(r.value);Nn.lastIndex=0,Nn.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Nn.source,input:r.value,inst:t}),e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(n.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:r.value,inst:t})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(n.protocol.endsWith(":")?n.protocol.slice(0,-1):n.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t}));return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t})}}}),uc=I("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=vu()),Ie.init(t,e)}),cc=I("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=gu),Ie.init(t,e)}),lc=I("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=lu),Ie.init(t,e)}),dc=I("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=du),Ie.init(t,e)}),pc=I("$ZodULID",(t,e)=>{e.pattern??(e.pattern=pu),Ie.init(t,e)}),mc=I("$ZodXID",(t,e)=>{e.pattern??(e.pattern=mu),Ie.init(t,e)}),fc=I("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=fu),Ie.init(t,e)}),gc=I("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=_u(e)),Ie.init(t,e)}),hc=I("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Iu),Ie.init(t,e)}),yc=I("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Su(e)),Ie.init(t,e)}),bc=I("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=hu),Ie.init(t,e)}),vc=I("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=wi),Ie.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.format="ipv4"})}),wc=I("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=xi),Ie.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t})}}}),xc=I("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=wu),Ie.init(t,e)}),Rc=I("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=xu),Ie.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t})}}});i(Pc,"isValidBase64");Ic=I("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ru),Ie.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Pc(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t})}});i(bh,"isValidBase64URL");Sc=I("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Ri),Ie.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{bh(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t})}}),_c=I("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Pu),Ie.init(t,e)});i(vh,"isValidJWT");kc=I("$ZodJWT",(t,e)=>{Ie.init(t,e),t._zod.check=r=>{vh(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t})}}),$i=I("$ZodNumber",(t,e)=>{ae.init(t,e),t._zod.pattern=t._zod.bag.pattern??Tu,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),Ec=I("$ZodNumber",(t,e)=>{Uu.init(t,e),$i.init(t,e)}),Un=I("$ZodBoolean",(t,e)=>{ae.init(t,e),t._zod.pattern=Ou,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),Ti=I("$ZodBigInt",(t,e)=>{ae.init(t,e),t._zod.pattern=Eu,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=BigInt(r.value)}catch{}let{value:o}=r;return typeof o=="bigint"||r.issues.push({expected:"bigint",code:"invalid_type",input:o,inst:t}),r}}),$c=I("$ZodBigInt",(t,e)=>{Du.init(t,e),Ti.init(t,e)}),Tc=I("$ZodSymbol",(t,e)=>{ae.init(t,e),t._zod.parse=(r,n)=>{let{value:o}=r;return typeof o=="symbol"||r.issues.push({expected:"symbol",code:"invalid_type",input:o,inst:t}),r}}),Oc=I("$ZodUndefined",(t,e)=>{ae.init(t,e),t._zod.pattern=Au,t._zod.values=new Set([void 0]),t._zod.parse=(r,n)=>{let{value:o}=r;return typeof o>"u"||r.issues.push({expected:"undefined",code:"invalid_type",input:o,inst:t}),r}}),Cc=I("$ZodNull",(t,e)=>{ae.init(t,e),t._zod.pattern=Cu,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let{value:o}=r;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),Ac=I("$ZodAny",(t,e)=>{ae.init(t,e),t._zod.parse=r=>r}),Dn=I("$ZodUnknown",(t,e)=>{ae.init(t,e),t._zod.parse=r=>r}),Nc=I("$ZodNever",(t,e)=>{ae.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)}),Lc=I("$ZodVoid",(t,e)=>{ae.init(t,e),t._zod.parse=(r,n)=>{let{value:o}=r;return typeof o>"u"||r.issues.push({expected:"void",code:"invalid_type",input:o,inst:t}),r}}),zc=I("$ZodDate",(t,e)=>{ae.init(t,e),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=new Date(r.value)}catch{}let o=r.value,s=o instanceof Date;return s&&!Number.isNaN(o.getTime())||r.issues.push({expected:"date",code:"invalid_type",input:o,...s?{received:"Invalid Date"}:{},inst:t}),r}});i(ah,"handleArrayResult");Uc=I("$ZodArray",(t,e)=>{ae.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let a=0;a<o.length;a++){let u=o[a],c=e.element._zod.run({value:u,issues:[]},n);c instanceof Promise?s.push(c.then(l=>ah(l,r,a))):ah(c,r,a)}return s.length?Promise.all(s).then(()=>r):r}});i(ki,"handleObjectResult");i(uh,"handleOptionalObjectResult");Dc=I("$ZodObject",(t,e)=>{ae.init(t,e);let r=Sn(()=>{let p=Object.keys(e.shape),m=tu(e.shape);return{shape:e.shape,keys:p,keySet:new Set(p),numKeys:p.length,optionalKeys:new Set(m)}});we(t._zod,"disc",()=>{let p=e.shape,m=new Map,f=!1;for(let h in p){let w=p[h]._zod;if(w.values||w.disc){f=!0;let x={values:new Set(w.values??[]),maps:w.disc?[w.disc]:[]};m.set(h,x)}}if(f)return m});let n=i(p=>{let m=new Ln(["shape","payload","ctx"]),{keys:f,optionalKeys:h}=r.value,w=i(_=>{let N=er(_);return`shape[${N}]._zod.run({ value: input[${N}], issues: [] }, ctx)`},"parseStr");m.write("const input = payload.value;");let x=Object.create(null);for(let _ of f)x[_]=di(15);m.write("const newResult = {}");for(let _ of f)if(h.has(_)){let N=x[_];m.write(`const ${N} = ${w(_)};`);let U=er(_);m.write(`
@@ -84,7 +84,7 @@ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.
84
84
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!_.has("X-Amz-Expires")&&_.set("X-Amz-Expires","86400"),_.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),_.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),_.set("X-Amz-SignedHeaders",this.signedHeaders)),this.service==="s3")try{this.encodedPath=decodeURIComponent(this.url.pathname.replace(/\+/g," "))}catch{this.encodedPath=this.url.pathname}else this.encodedPath=this.url.pathname.replace(/\/+/g,"/");w||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Vg(this.encodedPath);let N=new Set;this.encodedSearch=[...this.url.searchParams].filter(([U])=>{if(!U)return!1;if(this.service==="s3"){if(N.has(U))return!1;N.add(U)}return!0}).map(U=>U.map(z=>Vg(encodeURIComponent(z)))).sort(([U,z],[k,q])=>U<k?-1:U>k?1:z<q?-1:z>q?1:0).map(U=>U.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),r=[this.secretAccessKey,e,this.region,this.service].join(),n=this.cache.get(r);if(!n){let o=await Rn("AWS4"+this.secretAccessKey,e),s=await Rn(o,this.region),a=await Rn(s,this.service);n=await Rn(a,"aws4_request"),this.cache.set(r,n)}return qa(await Rn(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,qa(await Bg(await this.canonicalString()))].join(`
85
85
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
86
86
  `,this.signedHeaders,await this.hexBodyHash()].join(`
87
- `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new j("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=qa(await Bg(this.body||""))}return e}};async function Rn(t,e){let r=await crypto.subtle.importKey("raw",typeof t=="string"?Ha.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,Ha.encode(e))}i(Rn,"hmac");async function Bg(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Ha.encode(t):t)}i(Bg,"hash");function qa(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}i(qa,"buf2hex");function Vg(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(Vg,"encodeRfc3986");function Wx(t,e){let{hostname:r,pathname:n}=t,o=r.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")r.startsWith("iot.")?s="execute-api":r.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in Fg?[Fg[s],a]:[s,a]}i(Wx,"guessServiceRegion");function Kx(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}i(Kx,"b64ToUint6");function Gg(t,e){let r=t.replace(/[^A-Za-z0-9+/]/g,""),n=r.length,o=e?Math.ceil((n*3+1>>2)/e)*e:n*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<n;d++)if(u=d&3,c|=Kx(r.charCodeAt(d))<<6*(3-u),u===3||n-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(Gg,"base64Decode");function ci(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}i(ci,"uint6ToB64");function Jg(t){let e=2,r="",n=t.length,o=0;for(let s=0;s<n;s++)e=s%3,o|=t[s]<<(16>>>e&24),(e===2||t.length-s===1)&&(r+=String.fromCodePoint(ci(o>>>18&63),ci(o>>>12&63),ci(o>>>6&63),ci(o&63)),o=0);return r.substring(0,r.length-2+e)+(e===2?"":e===1?"=":"==")}i(Jg,"base64Encode");function Pr(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}i(Pr,"numberToString");function Qx(t){let e=t.getTimezoneOffset(),r=Math.abs(e),n=e>0?"-":"+",o=Pr(Math.floor(r/60)),s=Pr(r%60);return`${n}${o}${s}`}i(Qx,"getCLFOffset");function Ba(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],r=Pr(t.getDate()),n=e[t.getMonth()],o=t.getFullYear(),s=Pr(t.getHours()),a=Pr(t.getMinutes()),u=Pr(t.getSeconds()),c=Qx(t);return`${r}/${n}/${o}:${s}:${a}:${u} ${c}`}i(Ba,"toCLFDate");var Wg=Me("zuplo:runtime"),Xx="X-Amzn-Trace-Id",Yx="x-amzn-errortype",Kg=[],eR=i(async(t,e,r)=>{let n=r;for await(let o of Kg)n=await o(t,e,r);return n},"onSendingAwsLambdaEvent"),We=class extends j{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,r){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=r.get(Xx)??void 0,this.errorType=r.get(Yx)??void 0}},tR={addSendingAwsLambdaEventHook:i(t=>{Kg.push(t)},"addSendingAwsLambdaEventHook")};async function rR(t,e){b("handler.aws-lambda");let{accessKeyId:r,secretAccessKey:n,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!r)throw new y("awsAccessKeyId is not set in the handler options");if(!n)throw new y("secretAccessKey is not set in the handler options");if(!o)throw new y("region is not set in the handler options");if(!s)throw new y("functionName is not set in the handler options");let l=new Rr({accessKeyId:r,secretAccessKey:n}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Wg(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await sR(t,{binaryMediaTypes:c}),{options:f}=e.route.handler,h;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?h=iR(t,e):h=await oR(t,e,{useAwsResourcePathStyle:u}),Wg("Calling onSendingAwsLambdaEvent hook");let w=await eR(t,e,h);w.body=p,w.isBase64Encoded=m;let x=await l.fetch(d,{body:JSON.stringify(w)});try{return nR(x)}catch($){if($ instanceof We){let _=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&f.returnAmazonTraceIdHeader&&$.traceId?{AMZN_TRACE_ID_HEADER:$.traceId}:void 0;return A.internalServerError(t,e,void 0,_)}throw $}}i(rR,"awsLambdaHandler");async function nR(t){let e;try{e=await t.json()}catch{throw new We("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new We(e.message,t.headers):new We(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new We(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let r=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new We(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,s]of Object.entries(e.headers))r.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new We(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);r.set("cookie",e.cookies.join(";"))}let n;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new We(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new We("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new We("Response was set to base64 encoded but body was not a string",t.headers);n=Gg(e.body)}else"body"in e&&typeof e.body=="string"?n=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?n=JSON.stringify(e.body):n=null;if(n!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new We(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([n]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));n=await new Response(o).arrayBuffer()}return new Response(n,{headers:r,status:e.statusCode})}i(nR,"getResponse");async function oR(t,e,{useAwsResourcePathStyle:r}){let n={},o={};t.headers.forEach((l,d)=>{n[d]=l,o[d]=[l]});let s=t.query,a={};for(let[l,d]of Object.entries(s))a[l]||(a[l]=[]),a[l].push(d);let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:n,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Ba(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:uR(e.route.path,r),stage:null},pathParameters:t.params,stageVariables:null}}i(oR,"buildEventVersion1");function iR(t,e){let r={};t.headers.forEach((s,a)=>{r[a]=s});let n=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:n.pathname,rawQueryString:n.search,cookies:[],headers:r,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:n.hostname,domainPrefix:null,http:{method:t.method,path:n.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Ba(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}i(iR,"buildEventVersion2");async function sR(t,{binaryMediaTypes:e}){let r,n=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")r=null;else if(e&&o&&aR(e,o)){let s=await t.arrayBuffer();r=Jg(new Uint8Array(s)),n=!0}else r=await t.clone().text();return[r,n]}i(sR,"getBodyResult");function aR(t,e){let r=e.split(";")[0].trim().toLowerCase();return t.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}i(aR,"matchesContentType");function uR(t,e=!1){if(!e)return t;let r=Ma(t),n=Hg(t),o={};return r.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),n(o)}i(uR,"getResourcePath");var cR=[502,503,504];async function Ir(t,e){if(cR.includes(t.status)){let r=ue.getLogger(e),o=await t.clone().text(),s={};for(let[a,u]of t.headers)s[a]=u;r.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:s})}}i(Ir,"logBadGatewayResponses");var Va;function Zt(t){if(Va===void 0){let r=R.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),Va=r}return t.log[Va]}i(Zt,"getHandlerUserLogFunction");async function lR(t,e){b("handler.open-api");let r=R.instance.build.BUILD_ID,{buildAssetsUrl:n}=R.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new y("Open API Spec Handler must have 'openApiFilePath' specified");let a=dR(s);if(!a.isValid)throw new y(a.error);let u=`${n}/${r}${s.substring(1)}`,c=await B.fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return A.notFound(t,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json","content-encoding":c.headers.get("content-encoding")||"",vary:"Accept-Encoding"},status:c.status,statusText:c.statusText});return Ir(l,e),l}i(lR,"openApiSpecHandler");var dR=i(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function pR(t,e){b("handler.redirect");let r=e.route.handler.options;if(!r.location)throw new y("Redirect Handler must have 'location' specified");let n=r.status??302;return new Response(null,{status:n,headers:{location:r.location}})}i(pR,"redirectHandler");async function mR(t){if(b("handler.zuplo-service-proxy"),Object.entries(t.params).length!==1)throw new y("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(t.params.path,R.instance.zuploEdgeApiUrl),r=new Headers(t.headers);return r.set("Authorization",`Bearer ${R.instance.authApiJWT}`),B.fetch(e,{method:t.method,headers:r,body:t.body})}i(mR,"zuploServiceProxy");function fR(t,e){let r=t.endsWith("/"),n=e.startsWith("/");return r&&n?`${t.substring(0,t.length-1)}${e}`:!r&&!n?`${t}/${e}`:`${t}${e}`}i(fR,"join");async function gR(t,e){b("handler.url-forward");let r=Zt(e),n=e.route.handler.options,o=n.forwardSearch!==!1,s;if(R.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?s=n.followRedirects===!0?"follow":"manual":typeof n.followRedirects<"u"&&b("handler.url-forward.follow-redirects"),!n.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!n||typeof n.__rewriteFunction!="function")throw new y("Invalid options for this route");let a=jt(e),u=new URL(t.url),c=n.__rewriteFunction(t,a),l=fR(c,u.pathname),d=o?`${l}${u.search}`:l.toString(),p=Date.now();r(`URL Forwarding to '${d}'`);let m=await fetch(d,{method:t.method,body:t.body,headers:t.headers,redirect:s}),f=Date.now()-p;return r(`URL Forward received response ${m.status} - ${m.statusText} in ${f}ms`),Ir(m,e),m}i(gR,"urlForwardHandler");var hR=i((t,e)=>{let r=new URL(t),n=new URL(e);for(let[o,s]of n.searchParams.entries())r.searchParams.append(o,s);return r.toString()},"addQuery");async function yR(t,e){b("handler.url-rewrite");let r=Zt(e),n=e.route.handler.options,o=n.forwardSearch!==!1,s=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new y("Invalid options for this route");let a=jt(e),u=n.__rewriteFunction(t,a),c=o?hR(u,t.url):u,l=Date.now();r(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Ir(d,e),d}i(yR,"urlRewriteHandler");async function bR(t,e){b("handler.websocket");let r=e.route.handler.options,n=Zt(e);if(!r||!r.rewritePattern)throw new y("WebSocket Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return A.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let s=jt(e),a=r.__rewriteFunction(t,s),u=Date.now();n(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:t.method,headers:t.headers,body:t.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return n(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(bR,"webSocketHandler");async function vR(t,e){let r=be.instance.runtimeSettings.developerPortal.urls?.urls?.[0];if(!r)throw new y("Developer portal URL is not configured.");let n=wR(t.url,r);return e.log.info(`Redirecting from legacy dev portal to ${n}`),new Response(null,{status:301,headers:{location:n}})}i(vR,"redirectLegacyDevPortal");function wR(t,e){let r=new URL(t),n=r.pathname.split("/")[1];if(!n)throw new y("The request URL does not contain a valid developer portal base path. This handler cannot be used on a root path");return r.hostname=new URL(e).hostname,r.pathname=r.pathname.substring(n.length+1),r.toString()}i(wR,"getDevPortalRedirectUrl");var Ga=i((t,e)=>t.map((n,o)=>{let s;if(typeof n.module=="object"&&(s=n.module[n.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${n.export}`;throw new y(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Qg=i(async(t,e,r,n,o,s)=>{let a=t.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,r,e,n,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Xg(t,e,r,n,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",s=>{n.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),t.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Qg(c,t,e,r,n,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(n.log.error);n.waitUntil(u)}catch(a){n.log.error(a)}})}i(Xg,"wireUpListeners");async function xR(t,e){b("handler.websocket-pipeline");let r=e.route.handler.options,n=Zt(e);if(!r||!r.rewritePattern)throw new y("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return A.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let s=jt(e),a=r.__rewriteFunction(t,s),u=Date.now();n(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:t.method,headers:t.headers,body:t.body});if(c.status!==101||!c.webSocket){let x=await c.text(),$=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${x}'`;throw new Error($)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-u;n(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${m}ms`);let f=c.webSocket;f.accept(),p.accept();let h=r.policies&&r.policies.inbound?Ga(r.policies.inbound,"inbound"):[],w=r.policies&&r.policies.outbound?Ga(r.policies.outbound,"outbound"):[];return Xg(p,f,t,e,h),Xg(f,p,t,e,w),new Response(null,{status:101,webSocket:d})}i(xR,"webSocketPipelineHandler");Le();Le();uo();fs();var uk=g.object({jsonrpc:g.literal(Ht),id:Nr,error:g.object({code:g.number().int(),message:g.string(),data:g.optional(g.unknown())})}).strict();gs();zr();Ur();var co=i(t=>jb.safeParse(t).success,"isJSONRPCRequest"),Mb=i(t=>Db.safeParse(t).success,"isJSONRPCNotification"),hs=i(t=>Zb.safeParse(t).success,"isJSONRPCResponse");var lo=class{static{i(this,"NoOpLogger")}debug(){}info(){}warn(){}error(){}};function ys(){return new lo}i(ys,"createDefaultLogger");Le();zr();Ur();Le();var qb=g.object({experimental:g.optional(g.object({}).loose()),roots:g.optional(g.object({listChanged:g.optional(g.boolean())}).loose()),sampling:g.optional(g.object({}).loose()),elicitation:g.optional(g.object({}).loose())}).loose(),Hb=g.object({experimental:g.optional(g.object({}).loose()),logging:g.optional(g.object({}).loose()),completions:g.optional(g.object({}).loose()),prompts:g.optional(g.object({listChanged:g.optional(g.boolean())}).loose()),resources:g.optional(g.object({subscribe:g.optional(g.boolean()),listChanged:g.optional(g.boolean())}).loose()),tools:g.optional(g.object({listChanged:g.optional(g.boolean())}).loose())}).loose();Le();po();var xp=ar.extend({version:g.string()});var Fb=at.extend({method:g.literal("initialize"),params:st.extend({protocolVersion:g.string(),capabilities:qb,clientInfo:xp})}),Uq=wt.extend({protocolVersion:g.string(),capabilities:Hb,serverInfo:xp,instructions:g.optional(g.string())});Le();gs();zr();Ur();po();Pp();var kk=g.object({title:g.optional(g.string()),readOnlyHint:g.optional(g.boolean()),destructiveHint:g.optional(g.boolean()),idempotentHint:g.optional(g.boolean()),openWorldHint:g.optional(g.boolean())}).loose(),Ek=ar.extend({description:g.optional(g.string()),inputSchema:g.object({type:g.literal("object"),properties:g.optional(g.record(g.string(),g.object({}).loose())),required:g.optional(g.array(g.string()))}).loose(),outputSchema:g.optional(g.object({type:g.literal("object"),properties:g.optional(g.record(g.string(),g.object({}).loose())),required:g.optional(g.array(g.string()))}).loose()),annotations:g.optional(kk),_meta:g.optional(g.object({}).loose())}),u1=Dr.extend({method:g.literal("tools/list")}),c1=jr.extend({tools:g.array(Ek)}),ev=at.extend({method:g.literal("tools/call"),params:st.extend({name:g.string(),arguments:g.optional(g.record(g.string(),g.unknown()))})}),l1=g.lazy(()=>{let{TextContentSchema:t,ImageContentSchema:e,AudioContentSchema:r,EmbeddedResourceSchema:n}=(Jb(),yf(Gb)),{ResourceLinkSchema:o}=(Yb(),yf(Xb));return wt.extend({content:g.array(g.discriminatedUnion("type",[t,e,r,o,n])),structuredContent:g.optional(g.record(g.string(),g.unknown())),isError:g.optional(g.boolean())})}),d1=Lr.extend({method:g.literal("notifications/tools/list_changed")});var _p="2025-06-18",kp="2025-03-26",Ep="2024-11-05",$p="2024-10-07",Tp=[_p,kp,Ep,$p];var bs=class{static{i(this,"MCPServer")}capabilities;tools=new Map;name;version;instructions;logger;constructor(e){this.name=e.name||"MCP Server",this.version=e.version||"1.0.0",this.instructions=e.instructions||void 0,this.logger=e.logger||ys(),this.capabilities={tools:{supported:!0,available:[]},...e.capabilities}}withTransport(e){e.onMessage(async r=>{try{if(co(r)){let n=await this.handleRequest(r);if(n)return await e.send(n),n}else{if(Mb(r))return await this.handleNotification(r),null;if(hs(r))return this.logger.debug("Received response:",r),null}}catch(n){if(this.logger.error("Error processing message:",n),co(r)){let o={jsonrpc:"2.0",id:r.id,error:{code:-32603,message:n instanceof Error?n.message:"Internal error"}};return await e.send(o),o}}return null})}getTool(e){return this.tools.get(e)?.tool}getTools(){let e=new Map;for(let[r,n]of this.tools.entries())e.set(r,n.tool);return e}getCapabilities(){return{...this.capabilities}}addTool(e){let{name:r,validator:n,handler:o,description:s=`Execute the ${r} tool`,outputSchema:a}=e,c={tool:{name:r,description:s,inputSchema:n.jsonSchema,...a&&{outputSchema:a}},validator:n,handler:o};this.tools.set(r,c),this.updateAvailableTools()}removeTool(e){let r=this.tools.delete(e);return r&&this.updateAvailableTools(),r}getToolDefinitions(){return Array.from(this.tools.values()).map(e=>e.tool)}async handleRequest(e){try{switch(e.method){case"ping":return this.handlePing(e);case"initialize":return this.handleInitialize(e);case"tools/list":return this.handleToolListRequest(e);case"tools/call":return this.handleToolCallRequest(e);default:return{jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Method "${e.method}" not found`}}}}catch(r){return this.logger.error("Error handling request:",r),{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Internal error"}}}}async handleNotification(e){this.logger.debug("Received notification:",e.method)}handlePing(e){return{jsonrpc:"2.0",id:e.id,result:{}}}handleInitialize(e){let r=Fb.safeParse(e);if(!r.success){let o=g.treeifyError(r.error),s=g.prettifyError(r.error);return{jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid request parameters: ${s}`,data:o}}}let n=r.data.params.protocolVersion;switch(n){case _p:case kp:case Ep:case $p:{let o={protocolVersion:n,capabilities:this.getCapabilities(),serverInfo:{name:this.name,version:this.version},...this.instructions?{instructions:this.instructions}:{}};return{jsonrpc:"2.0",id:e.id,result:o}}default:return{jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Unsupported protocol version: ${n} - supported versions: ${Tp}`,data:{supportedVersions:Tp}}}}}async handleToolListRequest(e){let n={tools:Array.from(this.tools.entries()).map(([o,s])=>s.tool)};return{jsonrpc:"2.0",id:e.id,result:n}}async handleToolCallRequest(e){let r=ev.safeParse(e);if(!r.success)return this.logger.warn("Could not validate tool call:",r.error),{jsonrpc:"2.0",id:e.id,error:{code:-32600,message:`Invalid request ${r.error}`}};let n=r.data,o=n.params.name,s=this.tools.get(o);if(!s)return{jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Tool "${o}" not found`}};let a=n.params.arguments??{},u=s.validator.parse(a);if(!u.success)return{jsonrpc:"2.0",id:e.id,error:{code:-32602,message:u.errorMessage?`Invalid arguments for tool '${o}': ${u.errorMessage}`:`Invalid arguments for tool '${o}'`,data:u.errorData}};try{let c=u.data,l=await s.handler(c);return{jsonrpc:"2.0",id:e.id,result:l}}catch(c){return this.logger.error(`Error executing tool "${o}":`,c),{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:c instanceof Error?c.message:"Tool execution error"}}}}updateAvailableTools(){this.capabilities.tools&&(this.capabilities.tools.available=Array.from(this.tools.keys()))}};var Bt=class{static{i(this,"CustomValidator")}jsonSchema;parseFn;constructor(e,r){this.jsonSchema=e,this.parseFn=r}parse(e){return this.parseFn(e)}};var vs=class{static{i(this,"HTTPStreamableTransport")}messageHandler=null;closeCallback=null;options;connected=!1;enableStreaming=!1;sessions=new Map;streams=new Map;logger;constructor(e={},r=!1){this.options={timeout:30*60*1e3,enableSessions:!1,...e},this.logger=e.logger||ys(),r&&this.startSessionCleanup()}onError(e){throw new Error("Method not implemented.")}getSessionId(){throw new Error("Method not implemented.")}setSessionId(e){throw new Error("Method not implemented.")}async connect(){this.connected=!0}async send(e){if(!this.connected)throw new Error("Transport not connected");if(hs(e)){for(let[r,n]of this.sessions.entries())for(let[o,s]of n.streams.entries())if(s.pendingRequests.has(e.id)){await this.sendToStream(s,e),s.pendingRequests.delete(e.id),s.pendingRequests.size===0&&await this.closeStream(r,o);return}}else for(let r of this.sessions.values()){let n=[...r.streams.values()][0];n&&(await this.sendToStream(n,e),co(e)&&n.pendingRequests.add(e.id))}}onMessage(e){this.messageHandler=e}onClose(e){this.closeCallback=e}async close(){this.connected=!1;for(let e of this.sessions.values()){for(let[r,n]of e.streams.entries())try{await n.writer.close()}catch(o){this.logger.warn("Error closing stream:",o)}e.streams.clear()}this.sessions.clear(),this.closeCallback&&this.closeCallback()}async handleRequest(e){if(!this.connected)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Transport not connected"},id:null}),{status:503,headers:{"Content-Type":"application/json"}});if(!this.messageHandler)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"No message handler registered"},id:null}),{status:500,headers:{"Content-Type":"application/json"}});let r=e.method.toUpperCase();try{this.validateOrigin(e);let n=e.headers.get("Mcp-Session-Id"),o;if(n&&(o=this.sessions.get(n),!o&&r!=="DELETE"))return new Response(null,{status:404});switch(r){case"POST":return await this.handlePostRequest(e,o);case"GET":return await this.handleGetRequest(e,o);case"DELETE":return await this.handleDeleteRequest(e,o?.id);default:return new Response(null,{status:405,headers:{Allow:"POST, GET, DELETE"}})}}catch(n){this.logger.error("Error handling request:",n);let o=400,s={jsonrpc:"2.0",error:{code:-32603,message:n||"Server error"},id:null};return new Response(JSON.stringify(s),{status:o,headers:{"Content-Type":"application/json"}})}}async handlePostRequest(e,r){let n=e.headers.get("Accept")||"";if(!n.includes("application/json")&&!n.includes("text/event-stream"))return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32600,message:"Not Acceptable: Client must accept application/json and text/event-stream"},id:null}),{status:406,headers:{"Content-Type":"application/json"}});let o=await this.extractJSONRPC(e);if(!o||Array.isArray(o)&&o.length===0)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}),{status:400,headers:{"Content-Type":"application/json"}});let s=Array.isArray(o)?o:[o],a=s.some(c=>this.isRequest(c)),u=r;if(this.options.enableSessions&&!u&&s.some(c=>this.isRequest(c)&&c.method==="initialize")){let c=this.generateFallbackUUID();u=this.createSession(c)}try{if(!a){for(let m of s)await this.messageHandler?.(m);return new Response(null,{status:202,headers:u?{"Mcp-Session-Id":u.id}:void 0})}if(!this.enableStreaming){let m=[];for(let w of s)if(this.isRequest(w)){let x=await this.messageHandler?.(w);x&&m.push(x)}else await this.messageHandler?.(w);let f=m.length===1?m[0]:m,h={"Content-Type":"application/json"};return u&&(h["Mcp-Session-Id"]=u.id),new Response(JSON.stringify(f),{status:200,headers:h})}let{stream:c,streamId:l}=this.createStream(u),d=[];for(let m of s)if(this.isRequest(m)){this.streams.get(l)?.pendingRequests.add(m.id);let f=this.messageHandler?.(m);d.push(f)}else await this.messageHandler?.(m);let p={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};return u&&(p["Mcp-Session-Id"]=u.id),new Response(c.readable,{headers:p})}catch(c){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:c||"Internal error"},id:null}),{status:500,headers:{"Content-Type":"application/json"}})}}async handleGetRequest(e,r){if(!(e.headers.get("Accept")||"").includes("text/event-stream"))return new Response(null,{status:406,headers:{"Content-Type":"application/json"}});if(this.options.enableSessions&&!r)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Session required"},id:null}),{status:400,headers:{"Content-Type":"application/json"}});let{stream:o,streamId:s}=this.createStream(r),a=e.headers.get("Last-Event-ID");a&&r&&await this.replayMessages(r,s,a);let u={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};return r&&(u["Mcp-Session-Id"]=r.id),new Response(o.readable,{headers:u})}async handleDeleteRequest(e,r){if(!r)return new Response(null,{status:400});if(this.options.enableSessions&&r){let n=this.sessions.get(r);if(n){for(let[o,s]of n.streams.entries())await this.closeStream(r,o);return this.sessions.delete(r),new Response(null,{status:204})}}return new Response(null,{status:404})}async sendToStream(e,r){try{let n=String(++e.eventCounter),o=JSON.stringify(r);e.messages.push(r),e.messages.length>100&&e.messages.shift();let s=`id: ${n}
87
+ `)}async hexBodyHash(){let e=this.headers.get("X-Amz-Content-Sha256");if(e==null){if(this.body&&typeof this.body!="string"&&!("byteLength"in this.body))throw new j("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=qa(await Bg(this.body||""))}return e}};async function Rn(t,e){let r=await crypto.subtle.importKey("raw",typeof t=="string"?Ha.encode(t):t,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",r,Ha.encode(e))}i(Rn,"hmac");async function Bg(t){return crypto.subtle.digest("SHA-256",typeof t=="string"?Ha.encode(t):t)}i(Bg,"hash");function qa(t){return Array.prototype.map.call(new Uint8Array(t),e=>("0"+e.toString(16)).slice(-2)).join("")}i(qa,"buf2hex");function Vg(t){return t.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}i(Vg,"encodeRfc3986");function Wx(t,e){let{hostname:r,pathname:n}=t,o=r.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[s,a]=(o||["",""]).slice(1,3);if(a==="us-gov")a="us-gov-west-1";else if(a==="s3"||a==="s3-accelerate")a="us-east-1",s="s3";else if(s==="iot")r.startsWith("iot.")?s="execute-api":r.startsWith("data.jobs.iot.")?s="iot-jobs-data":s=n==="/mqtt"?"iotdevicegateway":"iotdata";else if(s==="autoscaling"){let u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?s="application-autoscaling":u==="AnyScaleScalingPlannerFrontendService"&&(s="autoscaling-plans")}else a==null&&s.startsWith("s3-")?(a=s.slice(3).replace(/^fips-|^external-1/,""),s="s3"):s.endsWith("-fips")?s=s.slice(0,-5):a&&/-\d$/.test(s)&&!/-\d$/.test(a)&&([s,a]=[a,s]);return s in Fg?[Fg[s],a]:[s,a]}i(Wx,"guessServiceRegion");function Kx(t){return t>64&&t<91?t-65:t>96&&t<123?t-71:t>47&&t<58?t+4:t===43?62:t===47?63:0}i(Kx,"b64ToUint6");function Gg(t,e){let r=t.replace(/[^A-Za-z0-9+/]/g,""),n=r.length,o=e?Math.ceil((n*3+1>>2)/e)*e:n*3+1>>2,s=new Uint8Array(o),a,u,c=0,l=0;for(let d=0;d<n;d++)if(u=d&3,c|=Kx(r.charCodeAt(d))<<6*(3-u),u===3||n-d===1){for(a=0;a<3&&l<o;)s[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return s}i(Gg,"base64Decode");function ci(t){return t<26?t+65:t<52?t+71:t<62?t-4:t===62?43:t===63?47:65}i(ci,"uint6ToB64");function Jg(t){let e=2,r="",n=t.length,o=0;for(let s=0;s<n;s++)e=s%3,o|=t[s]<<(16>>>e&24),(e===2||t.length-s===1)&&(r+=String.fromCodePoint(ci(o>>>18&63),ci(o>>>12&63),ci(o>>>6&63),ci(o&63)),o=0);return r.substring(0,r.length-2+e)+(e===2?"":e===1?"=":"==")}i(Jg,"base64Encode");function Pr(t){let e=t.toString();return`${e.length===1?"0":""}${e}`}i(Pr,"numberToString");function Qx(t){let e=t.getTimezoneOffset(),r=Math.abs(e),n=e>0?"-":"+",o=Pr(Math.floor(r/60)),s=Pr(r%60);return`${n}${o}${s}`}i(Qx,"getCLFOffset");function Ba(t=new Date){if(!(t instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],r=Pr(t.getDate()),n=e[t.getMonth()],o=t.getFullYear(),s=Pr(t.getHours()),a=Pr(t.getMinutes()),u=Pr(t.getSeconds()),c=Qx(t);return`${r}/${n}/${o}:${s}:${a}:${u} ${c}`}i(Ba,"toCLFDate");var Wg=Me("zuplo:runtime"),Xx="X-Amzn-Trace-Id",Yx="x-amzn-errortype",Kg=[],eR=i(async(t,e,r)=>{let n=r;for await(let o of Kg)n=await o(t,e,r);return n},"onSendingAwsLambdaEvent"),We=class extends j{static{i(this,"AwsLambdaError")}traceId;errorType;constructor(e,r){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=r.get(Xx)??void 0,this.errorType=r.get(Yx)??void 0}},tR={addSendingAwsLambdaEventHook:i(t=>{Kg.push(t)},"addSendingAwsLambdaEventHook")};async function rR(t,e){b("handler.aws-lambda");let{accessKeyId:r,secretAccessKey:n,region:o,functionName:s,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!r)throw new y("awsAccessKeyId is not set in the handler options");if(!n)throw new y("secretAccessKey is not set in the handler options");if(!o)throw new y("region is not set in the handler options");if(!s)throw new y("functionName is not set in the handler options");let l=new Rr({accessKeyId:r,secretAccessKey:n}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${s}/invocations`;if(Wg(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await t.arrayBuffer()});let[p,m]=await sR(t,{binaryMediaTypes:c}),{options:f}=e.route.handler,h;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?h=iR(t,e):h=await oR(t,e,{useAwsResourcePathStyle:u}),Wg("Calling onSendingAwsLambdaEvent hook");let w=await eR(t,e,h);w.body=p,w.isBase64Encoded=m;let x=await l.fetch(d,{body:JSON.stringify(w)});try{return nR(x)}catch($){if($ instanceof We){let _=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&f.returnAmazonTraceIdHeader&&$.traceId?{AMZN_TRACE_ID_HEADER:$.traceId}:void 0;return A.internalServerError(t,e,void 0,_)}throw $}}i(rR,"awsLambdaHandler");async function nR(t){let e;try{e=await t.json()}catch{throw new We("Lambda response did not contain valid JSON",t.headers)}if(t.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new We(e.message,t.headers):new We(`Status: ${t.statusText}`,t.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new We(e.errorMessage,t.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:t.status,headers:{"content-type":"application/json"}});let r=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new We(`Response headers must be an object. Received ${typeof e.headers}`,t.headers);for(let[o,s]of Object.entries(e.headers))r.set(o,s)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new We(`Response cookies must be an array. Received ${typeof e.cookies}`,t.headers);r.set("cookie",e.cookies.join(";"))}let n;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new We(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,t.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new We("Response was set to base64 encoded but no body was set",t.headers);if(typeof e.body!="string")throw new We("Response was set to base64 encoded but body was not a string",t.headers);n=Gg(e.body)}else"body"in e&&typeof e.body=="string"?n=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?n=JSON.stringify(e.body):n=null;if(n!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new We(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,t.headers);let o=new Blob([n]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));n=await new Response(o).arrayBuffer()}return new Response(n,{headers:r,status:e.statusCode})}i(nR,"getResponse");async function oR(t,e,{useAwsResourcePathStyle:r}){let n={},o={};t.headers.forEach((l,d)=>{n[d]=l,o[d]=[l]});let s=t.query,a={};for(let[l,d]of Object.entries(s))a[l]||(a[l]=[]),a[l].push(d);let u=new URL(t.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:t.method,headers:n,multiValueHeaders:o,queryStringParameters:s,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:t.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:t.headers.get("CF-Connecting-IP"),user:null,userAgent:t.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Ba(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:uR(e.route.path,r),stage:null},pathParameters:t.params,stageVariables:null}}i(oR,"buildEventVersion1");function iR(t,e){let r={};t.headers.forEach((s,a)=>{r[a]=s});let n=new URL(t.url);return{version:"2.0",routeKey:null,rawPath:n.pathname,rawQueryString:n.search,cookies:[],headers:r,queryStringParameters:t.query,requestContext:{accountId:null,apiId:null,authentication:{clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},authorizer:{jwt:{claims:{},scopes:[]}},domainName:n.hostname,domainPrefix:null,http:{method:t.method,path:n.pathname,protocol:"HTTP/1.1",sourceIp:t.headers.get("CF-Connecting-IP"),userAgent:t.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Ba(),timeEpoch:new Date().valueOf()},pathParameters:t.params,stageVariables:null}}i(iR,"buildEventVersion2");async function sR(t,{binaryMediaTypes:e}){let r,n=!1,o=t.headers.get("content-type");if(t.method==="GET"||t.method==="HEAD")r=null;else if(e&&o&&aR(e,o)){let s=await t.arrayBuffer();r=Jg(new Uint8Array(s)),n=!0}else r=await t.clone().text();return[r,n]}i(sR,"getBodyResult");function aR(t,e){let r=e.split(";")[0].trim().toLowerCase();return t.findIndex(n=>n==="*/*"?!0:n.toLowerCase()===r)>-1}i(aR,"matchesContentType");function uR(t,e=!1){if(!e)return t;let r=Ma(t),n=Hg(t),o={};return r.forEach(s=>{typeof s=="string"?o[s]=`{${s}}`:o[s.name]=`{${s.name}}`}),n(o)}i(uR,"getResourcePath");var cR=[502,503,504];async function Ir(t,e){if(cR.includes(t.status)){let r=ue.getLogger(e),o=await t.clone().text(),s={};for(let[a,u]of t.headers)s[a]=u;r.warn(`BadGatewayResponse ${t.status}`,{status:t.status,statusText:t.statusText,body:o,headers:s})}}i(Ir,"logBadGatewayResponses");var Va;function Zt(t){if(Va===void 0){let r=R.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(r??"")||(r="debug"),Va=r}return t.log[Va]}i(Zt,"getHandlerUserLogFunction");async function lR(t,e){b("handler.open-api");let r=R.instance.build.BUILD_ID,{buildAssetsUrl:n}=R.instance,o=e.route.handler.options,{openApiFilePath:s}=o;if(!s)throw new y("Open API Spec Handler must have 'openApiFilePath' specified");let a=dR(s);if(!a.isValid)throw new y(a.error);let u=`${n}/${r}${s.substring(1)}`,c=await B.fetch(u,{method:t.method,body:t.body,headers:t.headers});if(c.status!==200)return A.notFound(t,e,{detail:"OpenAPI file could not be found."});let l={"content-type":"application/json",vary:"Accept-Encoding"};R.instance.isDeno||(l["content-encoding"]=c.headers.get("content-encoding")||"");let d=new Response(c.body,{headers:l,status:c.status,statusText:c.statusText});return Ir(d,e),d}i(lR,"openApiSpecHandler");var dR=i(t=>t.startsWith("./")?t.startsWith("./config")?t.endsWith(".oas.json")?{isValid:!0}:{isValid:!1,error:"'openApiFilePath' must point to a file ending in '.oas.json'"}:{isValid:!1,error:"'openApiFilePath' must point to a file in your /config directory"}:{isValid:!1,error:"'openApiFilePath' must start with './'"},"validateOpenApiPath");async function pR(t,e){b("handler.redirect");let r=e.route.handler.options;if(!r.location)throw new y("Redirect Handler must have 'location' specified");let n=r.status??302;return new Response(null,{status:n,headers:{location:r.location}})}i(pR,"redirectHandler");async function mR(t){if(b("handler.zuplo-service-proxy"),Object.entries(t.params).length!==1)throw new y("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(t.params.path,R.instance.zuploEdgeApiUrl),r=new Headers(t.headers);return r.set("Authorization",`Bearer ${R.instance.authApiJWT}`),B.fetch(e,{method:t.method,headers:r,body:t.body})}i(mR,"zuploServiceProxy");function fR(t,e){let r=t.endsWith("/"),n=e.startsWith("/");return r&&n?`${t.substring(0,t.length-1)}${e}`:!r&&!n?`${t}/${e}`:`${t}${e}`}i(fR,"join");async function gR(t,e){b("handler.url-forward");let r=Zt(e),n=e.route.handler.options,o=n.forwardSearch!==!1,s;if(R.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?s=n.followRedirects===!0?"follow":"manual":typeof n.followRedirects<"u"&&b("handler.url-forward.follow-redirects"),!n.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!n||typeof n.__rewriteFunction!="function")throw new y("Invalid options for this route");let a=jt(e),u=new URL(t.url),c=n.__rewriteFunction(t,a),l=fR(c,u.pathname),d=o?`${l}${u.search}`:l.toString(),p=Date.now();r(`URL Forwarding to '${d}'`);let m=await fetch(d,{method:t.method,body:t.body,headers:t.headers,redirect:s}),f=Date.now()-p;return r(`URL Forward received response ${m.status} - ${m.statusText} in ${f}ms`),Ir(m,e),m}i(gR,"urlForwardHandler");var hR=i((t,e)=>{let r=new URL(t),n=new URL(e);for(let[o,s]of n.searchParams.entries())r.searchParams.append(o,s);return r.toString()},"addQuery");async function yR(t,e){b("handler.url-rewrite");let r=Zt(e),n=e.route.handler.options,o=n.forwardSearch!==!1,s=n.followRedirects??!1;if(!n||typeof n.__rewriteFunction!="function")throw new y("Invalid options for this route");let a=jt(e),u=n.__rewriteFunction(t,a),c=o?hR(u,t.url):u,l=Date.now();r(`URL Rewriting to '${c}'`);let d=await fetch(c.toString(),{method:t.method,body:t.body,headers:t.headers,redirect:s?"follow":"manual"}),p=Date.now()-l;return r(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),Ir(d,e),d}i(yR,"urlRewriteHandler");async function bR(t,e){b("handler.websocket");let r=e.route.handler.options,n=Zt(e);if(!r||!r.rewritePattern)throw new y("WebSocket Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return A.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let s=jt(e),a=r.__rewriteFunction(t,s),u=Date.now();n(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:t.method,headers:t.headers,body:t.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return n(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}i(bR,"webSocketHandler");async function vR(t,e){let r=be.instance.runtimeSettings.developerPortal.urls?.urls?.[0];if(!r)throw new y("Developer portal URL is not configured.");let n=wR(t.url,r);return e.log.info(`Redirecting from legacy dev portal to ${n}`),new Response(null,{status:301,headers:{location:n}})}i(vR,"redirectLegacyDevPortal");function wR(t,e){let r=new URL(t),n=r.pathname.split("/")[1];if(!n)throw new y("The request URL does not contain a valid developer portal base path. This handler cannot be used on a root path");return r.hostname=new URL(e).hostname,r.pathname=r.pathname.substring(n.length+1),r.toString()}i(wR,"getDevPortalRedirectUrl");var Ga=i((t,e)=>t.map((n,o)=>{let s;if(typeof n.module=="object"&&(s=n.module[n.export]),!s||typeof s!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",u=`policy in position: ${o+1}, export name: ${n.export}`;throw new y(`${a} - Websocket policy must be a valid function (${u})`)}return s}),"getWebSocketPolicyFunctions"),Qg=i(async(t,e,r,n,o,s)=>{let a=t.data;if(s&&s.length>0){let u=[...s];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,r,e,n,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function Xg(t,e,r,n,o){t.addEventListener("close",()=>{e.close()}),t.addEventListener("error",s=>{n.log.error("WebSocket error: ",s),e.send(JSON.stringify(s))}),t.addEventListener("message",s=>{try{let u=i(async c=>{let l=await Qg(c,t,e,r,n,o);l!==void 0&&e.send(l)},"innerPipeline")(s).catch(n.log.error);n.waitUntil(u)}catch(a){n.log.error(a)}})}i(Xg,"wireUpListeners");async function xR(t,e){b("handler.websocket-pipeline");let r=e.route.handler.options,n=Zt(e);if(!r||!r.rewritePattern)throw new y("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=t.headers.get("Upgrade");if(!o||o!=="websocket")return A.badRequest(t,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!r||typeof r.__rewriteFunction!="function")throw new y("Invalid options for this route");let s=jt(e),a=r.__rewriteFunction(t,s),u=Date.now();n(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await fetch(a,{method:t.method,headers:t.headers,body:t.body});if(c.status!==101||!c.webSocket){let x=await c.text(),$=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${x}'`;throw new Error($)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-u;n(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${m}ms`);let f=c.webSocket;f.accept(),p.accept();let h=r.policies&&r.policies.inbound?Ga(r.policies.inbound,"inbound"):[],w=r.policies&&r.policies.outbound?Ga(r.policies.outbound,"outbound"):[];return Xg(p,f,t,e,h),Xg(f,p,t,e,w),new Response(null,{status:101,webSocket:d})}i(xR,"webSocketPipelineHandler");Le();Le();uo();fs();var uk=g.object({jsonrpc:g.literal(Ht),id:Nr,error:g.object({code:g.number().int(),message:g.string(),data:g.optional(g.unknown())})}).strict();gs();zr();Ur();var co=i(t=>jb.safeParse(t).success,"isJSONRPCRequest"),Mb=i(t=>Db.safeParse(t).success,"isJSONRPCNotification"),hs=i(t=>Zb.safeParse(t).success,"isJSONRPCResponse");var lo=class{static{i(this,"NoOpLogger")}debug(){}info(){}warn(){}error(){}};function ys(){return new lo}i(ys,"createDefaultLogger");Le();zr();Ur();Le();var qb=g.object({experimental:g.optional(g.object({}).loose()),roots:g.optional(g.object({listChanged:g.optional(g.boolean())}).loose()),sampling:g.optional(g.object({}).loose()),elicitation:g.optional(g.object({}).loose())}).loose(),Hb=g.object({experimental:g.optional(g.object({}).loose()),logging:g.optional(g.object({}).loose()),completions:g.optional(g.object({}).loose()),prompts:g.optional(g.object({listChanged:g.optional(g.boolean())}).loose()),resources:g.optional(g.object({subscribe:g.optional(g.boolean()),listChanged:g.optional(g.boolean())}).loose()),tools:g.optional(g.object({listChanged:g.optional(g.boolean())}).loose())}).loose();Le();po();var xp=ar.extend({version:g.string()});var Fb=at.extend({method:g.literal("initialize"),params:st.extend({protocolVersion:g.string(),capabilities:qb,clientInfo:xp})}),Uq=wt.extend({protocolVersion:g.string(),capabilities:Hb,serverInfo:xp,instructions:g.optional(g.string())});Le();gs();zr();Ur();po();Pp();var kk=g.object({title:g.optional(g.string()),readOnlyHint:g.optional(g.boolean()),destructiveHint:g.optional(g.boolean()),idempotentHint:g.optional(g.boolean()),openWorldHint:g.optional(g.boolean())}).loose(),Ek=ar.extend({description:g.optional(g.string()),inputSchema:g.object({type:g.literal("object"),properties:g.optional(g.record(g.string(),g.object({}).loose())),required:g.optional(g.array(g.string()))}).loose(),outputSchema:g.optional(g.object({type:g.literal("object"),properties:g.optional(g.record(g.string(),g.object({}).loose())),required:g.optional(g.array(g.string()))}).loose()),annotations:g.optional(kk),_meta:g.optional(g.object({}).loose())}),u1=Dr.extend({method:g.literal("tools/list")}),c1=jr.extend({tools:g.array(Ek)}),ev=at.extend({method:g.literal("tools/call"),params:st.extend({name:g.string(),arguments:g.optional(g.record(g.string(),g.unknown()))})}),l1=g.lazy(()=>{let{TextContentSchema:t,ImageContentSchema:e,AudioContentSchema:r,EmbeddedResourceSchema:n}=(Jb(),yf(Gb)),{ResourceLinkSchema:o}=(Yb(),yf(Xb));return wt.extend({content:g.array(g.discriminatedUnion("type",[t,e,r,o,n])),structuredContent:g.optional(g.record(g.string(),g.unknown())),isError:g.optional(g.boolean())})}),d1=Lr.extend({method:g.literal("notifications/tools/list_changed")});var _p="2025-06-18",kp="2025-03-26",Ep="2024-11-05",$p="2024-10-07",Tp=[_p,kp,Ep,$p];var bs=class{static{i(this,"MCPServer")}capabilities;tools=new Map;name;version;instructions;logger;constructor(e){this.name=e.name||"MCP Server",this.version=e.version||"1.0.0",this.instructions=e.instructions||void 0,this.logger=e.logger||ys(),this.capabilities={tools:{supported:!0,available:[]},...e.capabilities}}withTransport(e){e.onMessage(async r=>{try{if(co(r)){let n=await this.handleRequest(r);if(n)return await e.send(n),n}else{if(Mb(r))return await this.handleNotification(r),null;if(hs(r))return this.logger.debug("Received response:",r),null}}catch(n){if(this.logger.error("Error processing message:",n),co(r)){let o={jsonrpc:"2.0",id:r.id,error:{code:-32603,message:n instanceof Error?n.message:"Internal error"}};return await e.send(o),o}}return null})}getTool(e){return this.tools.get(e)?.tool}getTools(){let e=new Map;for(let[r,n]of this.tools.entries())e.set(r,n.tool);return e}getCapabilities(){return{...this.capabilities}}addTool(e){let{name:r,validator:n,handler:o,description:s=`Execute the ${r} tool`,outputSchema:a}=e,c={tool:{name:r,description:s,inputSchema:n.jsonSchema,...a&&{outputSchema:a}},validator:n,handler:o};this.tools.set(r,c),this.updateAvailableTools()}removeTool(e){let r=this.tools.delete(e);return r&&this.updateAvailableTools(),r}getToolDefinitions(){return Array.from(this.tools.values()).map(e=>e.tool)}async handleRequest(e){try{switch(e.method){case"ping":return this.handlePing(e);case"initialize":return this.handleInitialize(e);case"tools/list":return this.handleToolListRequest(e);case"tools/call":return this.handleToolCallRequest(e);default:return{jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Method "${e.method}" not found`}}}}catch(r){return this.logger.error("Error handling request:",r),{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:r instanceof Error?r.message:"Internal error"}}}}async handleNotification(e){this.logger.debug("Received notification:",e.method)}handlePing(e){return{jsonrpc:"2.0",id:e.id,result:{}}}handleInitialize(e){let r=Fb.safeParse(e);if(!r.success){let o=g.treeifyError(r.error),s=g.prettifyError(r.error);return{jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Invalid request parameters: ${s}`,data:o}}}let n=r.data.params.protocolVersion;switch(n){case _p:case kp:case Ep:case $p:{let o={protocolVersion:n,capabilities:this.getCapabilities(),serverInfo:{name:this.name,version:this.version},...this.instructions?{instructions:this.instructions}:{}};return{jsonrpc:"2.0",id:e.id,result:o}}default:return{jsonrpc:"2.0",id:e.id,error:{code:-32602,message:`Unsupported protocol version: ${n} - supported versions: ${Tp}`,data:{supportedVersions:Tp}}}}}async handleToolListRequest(e){let n={tools:Array.from(this.tools.entries()).map(([o,s])=>s.tool)};return{jsonrpc:"2.0",id:e.id,result:n}}async handleToolCallRequest(e){let r=ev.safeParse(e);if(!r.success)return this.logger.warn("Could not validate tool call:",r.error),{jsonrpc:"2.0",id:e.id,error:{code:-32600,message:`Invalid request ${r.error}`}};let n=r.data,o=n.params.name,s=this.tools.get(o);if(!s)return{jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Tool "${o}" not found`}};let a=n.params.arguments??{},u=s.validator.parse(a);if(!u.success)return{jsonrpc:"2.0",id:e.id,error:{code:-32602,message:u.errorMessage?`Invalid arguments for tool '${o}': ${u.errorMessage}`:`Invalid arguments for tool '${o}'`,data:u.errorData}};try{let c=u.data,l=await s.handler(c);return{jsonrpc:"2.0",id:e.id,result:l}}catch(c){return this.logger.error(`Error executing tool "${o}":`,c),{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:c instanceof Error?c.message:"Tool execution error"}}}}updateAvailableTools(){this.capabilities.tools&&(this.capabilities.tools.available=Array.from(this.tools.keys()))}};var Bt=class{static{i(this,"CustomValidator")}jsonSchema;parseFn;constructor(e,r){this.jsonSchema=e,this.parseFn=r}parse(e){return this.parseFn(e)}};var vs=class{static{i(this,"HTTPStreamableTransport")}messageHandler=null;closeCallback=null;options;connected=!1;enableStreaming=!1;sessions=new Map;streams=new Map;logger;constructor(e={},r=!1){this.options={timeout:30*60*1e3,enableSessions:!1,...e},this.logger=e.logger||ys(),r&&this.startSessionCleanup()}onError(e){throw new Error("Method not implemented.")}getSessionId(){throw new Error("Method not implemented.")}setSessionId(e){throw new Error("Method not implemented.")}async connect(){this.connected=!0}async send(e){if(!this.connected)throw new Error("Transport not connected");if(hs(e)){for(let[r,n]of this.sessions.entries())for(let[o,s]of n.streams.entries())if(s.pendingRequests.has(e.id)){await this.sendToStream(s,e),s.pendingRequests.delete(e.id),s.pendingRequests.size===0&&await this.closeStream(r,o);return}}else for(let r of this.sessions.values()){let n=[...r.streams.values()][0];n&&(await this.sendToStream(n,e),co(e)&&n.pendingRequests.add(e.id))}}onMessage(e){this.messageHandler=e}onClose(e){this.closeCallback=e}async close(){this.connected=!1;for(let e of this.sessions.values()){for(let[r,n]of e.streams.entries())try{await n.writer.close()}catch(o){this.logger.warn("Error closing stream:",o)}e.streams.clear()}this.sessions.clear(),this.closeCallback&&this.closeCallback()}async handleRequest(e){if(!this.connected)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Transport not connected"},id:null}),{status:503,headers:{"Content-Type":"application/json"}});if(!this.messageHandler)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"No message handler registered"},id:null}),{status:500,headers:{"Content-Type":"application/json"}});let r=e.method.toUpperCase();try{this.validateOrigin(e);let n=e.headers.get("Mcp-Session-Id"),o;if(n&&(o=this.sessions.get(n),!o&&r!=="DELETE"))return new Response(null,{status:404});switch(r){case"POST":return await this.handlePostRequest(e,o);case"GET":return await this.handleGetRequest(e,o);case"DELETE":return await this.handleDeleteRequest(e,o?.id);default:return new Response(null,{status:405,headers:{Allow:"POST, GET, DELETE"}})}}catch(n){this.logger.error("Error handling request:",n);let o=400,s={jsonrpc:"2.0",error:{code:-32603,message:n||"Server error"},id:null};return new Response(JSON.stringify(s),{status:o,headers:{"Content-Type":"application/json"}})}}async handlePostRequest(e,r){let n=e.headers.get("Accept")||"";if(!n.includes("application/json")&&!n.includes("text/event-stream"))return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32600,message:"Not Acceptable: Client must accept application/json and text/event-stream"},id:null}),{status:406,headers:{"Content-Type":"application/json"}});let o=await this.extractJSONRPC(e);if(!o||Array.isArray(o)&&o.length===0)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32700,message:"Parse error"},id:null}),{status:400,headers:{"Content-Type":"application/json"}});let s=Array.isArray(o)?o:[o],a=s.some(c=>this.isRequest(c)),u=r;if(this.options.enableSessions&&!u&&s.some(c=>this.isRequest(c)&&c.method==="initialize")){let c=this.generateFallbackUUID();u=this.createSession(c)}try{if(!a){for(let m of s)await this.messageHandler?.(m);return new Response(null,{status:202,headers:u?{"Mcp-Session-Id":u.id}:void 0})}if(!this.enableStreaming){let m=[];for(let w of s)if(this.isRequest(w)){let x=await this.messageHandler?.(w);x&&m.push(x)}else await this.messageHandler?.(w);let f=m.length===1?m[0]:m,h={"Content-Type":"application/json"};return u&&(h["Mcp-Session-Id"]=u.id),new Response(JSON.stringify(f),{status:200,headers:h})}let{stream:c,streamId:l}=this.createStream(u),d=[];for(let m of s)if(this.isRequest(m)){this.streams.get(l)?.pendingRequests.add(m.id);let f=this.messageHandler?.(m);d.push(f)}else await this.messageHandler?.(m);let p={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};return u&&(p["Mcp-Session-Id"]=u.id),new Response(c.readable,{headers:p})}catch(c){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:c||"Internal error"},id:null}),{status:500,headers:{"Content-Type":"application/json"}})}}async handleGetRequest(e,r){if(!(e.headers.get("Accept")||"").includes("text/event-stream"))return new Response(null,{status:406,headers:{"Content-Type":"application/json"}});if(this.options.enableSessions&&!r)return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32e3,message:"Session required"},id:null}),{status:400,headers:{"Content-Type":"application/json"}});let{stream:o,streamId:s}=this.createStream(r),a=e.headers.get("Last-Event-ID");a&&r&&await this.replayMessages(r,s,a);let u={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};return r&&(u["Mcp-Session-Id"]=r.id),new Response(o.readable,{headers:u})}async handleDeleteRequest(e,r){if(!r)return new Response(null,{status:400});if(this.options.enableSessions&&r){let n=this.sessions.get(r);if(n){for(let[o,s]of n.streams.entries())await this.closeStream(r,o);return this.sessions.delete(r),new Response(null,{status:204})}}return new Response(null,{status:404})}async sendToStream(e,r){try{let n=String(++e.eventCounter),o=JSON.stringify(r);e.messages.push(r),e.messages.length>100&&e.messages.shift();let s=`id: ${n}
88
88
  data: ${o}
89
89
 
90
90
  `;await e.writer.write(new TextEncoder().encode(s))}catch(n){this.logger.warn("Error sending to stream:",n)}}async closeStream(e,r){let n=this.sessions.get(e);if(!n)return;let o=n.streams.get(r);if(o){try{await o.writer.close()}catch(s){this.logger.warn("Error closing stream:",s)}n.streams.delete(r),this.streams.delete(r)}}createSession(e){let r={id:e,createdAt:Date.now(),lastActivity:Date.now(),streams:new Map};return this.sessions.set(e,r),r}createStream(e){let r=new TransformStream,n=r.writable.getWriter(),o=crypto.randomUUID?.()||this.generateFallbackUUID(),s={id:o,writer:n,eventCounter:0,messages:[],pendingRequests:new Set};return this.streams.set(o,s),e&&(e.streams.set(o,s),e.lastActivity=Date.now()),{stream:r,streamId:o}}async replayMessages(e,r,n){for(let o of e.streams.values()){if(o.id===r)continue;let s=Number.parseInt(n,10);if(Number.isNaN(s))continue;let a=o.messages.slice(s),u=this.streams.get(r);if(u&&a.length>0)for(let c of a)await this.sendToStream(u,c)}}startSessionCleanup(){setInterval(()=>{let e=Date.now();for(let[r,n]of this.sessions.entries()){let o=this.options.timeout??6e4;if(e-n.lastActivity>o){for(let[s,a]of n.streams.entries()){try{a.writer.close().catch(u=>this.logger.warn("Error closing stream:",u))}catch(u){this.logger.warn("Error closing stream:",u)}this.streams.delete(s)}this.sessions.delete(r)}}},6e4)}async extractJSONRPC(e){try{let n=await e.clone().text();if(!n)throw new Error("Empty request body");return JSON.parse(n)}catch(r){throw new Error(`Failed to parse JSON-RPC message: ${r}`)}}validateOrigin(e){let r=e.headers.get("Origin");if(r&&!this.isValidOrigin(r))throw new Error("Invalid origin")}isValidOrigin(e){return!0}isRequest(e){return e!==null&&typeof e=="object"&&"jsonrpc"in e&&e.jsonrpc==="2.0"&&"method"in e&&"id"in e&&e.id!==null&&e.id!==void 0}generateFallbackUUID(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let r=Math.random()*16|0;return(e==="x"?r:r&3|8).toString(16)})}};Le();var go=class{static{i(this,"R")}type=3;name="";prefix="";value="";suffix="";modifier=3;constructor(t,e,r,n,o,s){this.type=t,this.name=e,this.prefix=r,this.value=n,this.suffix=o,this.modifier=s}hasCustomName(){return this.name!==""&&typeof this.name!="number"}},$k=/[$_\p{ID_Start}]/u,Tk=/[$_\u200C\u200D\p{ID_Continue}]/u,Cp=".*";function Ok(t,e){return(e?/^[\x00-\xFF]*$/:/^[\x00-\x7F]*$/).test(t)}i(Ok,"Re");function nv(t,e=!1){let r=[],n=0;for(;n<t.length;){let o=t[n],s=i(function(a){if(!e)throw new TypeError(a);r.push({type:"INVALID_CHAR",index:n,value:t[n++]})},"c");if(o==="*"){r.push({type:"ASTERISK",index:n,value:t[n++]});continue}if(o==="+"||o==="?"){r.push({type:"OTHER_MODIFIER",index:n,value:t[n++]});continue}if(o==="\\"){r.push({type:"ESCAPED_CHAR",index:n++,value:t[n++]});continue}if(o==="{"){r.push({type:"OPEN",index:n,value:t[n++]});continue}if(o==="}"){r.push({type:"CLOSE",index:n,value:t[n++]});continue}if(o===":"){let a="",u=n+1;for(;u<t.length;){let c=t.substr(u,1);if(u===n+1&&$k.test(c)||u!==n+1&&Tk.test(c)){a+=t[u++];continue}break}if(!a){s(`Missing parameter name at ${n}`);continue}r.push({type:"NAME",index:n,value:a}),n=u;continue}if(o==="("){let a=1,u="",c=n+1,l=!1;if(t[c]==="?"){s(`Pattern cannot start with "?" at ${c}`);continue}for(;c<t.length;){if(!Ok(t[c],!1)){s(`Invalid character '${t[c]}' at ${c}.`),l=!0;break}if(t[c]==="\\"){u+=t[c++]+t[c++];continue}if(t[c]===")"){if(a--,a===0){c++;break}}else if(t[c]==="("&&(a++,t[c+1]!=="?")){s(`Capturing groups are not allowed at ${c}`),l=!0;break}u+=t[c++]}if(l)continue;if(a){s(`Unbalanced pattern at ${n}`);continue}if(!u){s(`Missing pattern at ${n}`);continue}r.push({type:"REGEX",index:n,value:u}),n=c;continue}r.push({type:"CHAR",index:n,value:t[n++]})}return r.push({type:"END",index:n,value:""}),r}i(nv,"v");function ov(t,e={}){let r=nv(t);e.delimiter??="/#?",e.prefixes??="./";let n=`[^${rt(e.delimiter)}]+?`,o=[],s=0,a=0,u="",c=new Set,l=i(N=>{if(a<r.length&&r[a].type===N)return r[a++].value},"a"),d=i(()=>l("OTHER_MODIFIER")??l("ASTERISK"),"f"),p=i(N=>{let U=l(N);if(U!==void 0)return U;let{type:z,index:k}=r[a];throw new TypeError(`Unexpected ${z} at ${k}, expected ${N}`)},"d"),m=i(()=>{let N="",U;for(;U=l("CHAR")??l("ESCAPED_CHAR");)N+=U;return N},"T"),f=i(N=>N,"Se"),h=e.encodePart||f,w="",x=i(N=>{w+=N},"U"),$=i(()=>{w.length&&(o.push(new go(3,"","",h(w),"",3)),w="")},"$"),_=i((N,U,z,k,q)=>{let K=3;switch(q){case"?":K=1;break;case"*":K=0;break;case"+":K=2;break}if(!U&&!z&&K===3){x(N);return}if($(),!U&&!z){if(!N)return;o.push(new go(3,"","",h(N),"",K));return}let G;z?z==="*"?G=Cp:G=z:G=n;let C=2;G===n?(C=1,G=""):G===Cp&&(C=0,G="");let E;if(U?E=U:z&&(E=s++),c.has(E))throw new TypeError(`Duplicate name '${E}'.`);c.add(E),o.push(new go(C,E,h(N),G,h(k),K))},"V");for(;a<r.length;){let N=l("CHAR"),U=l("NAME"),z=l("REGEX");if(!U&&!z&&(z=l("ASTERISK")),U||z){let q=N??"";e.prefixes.indexOf(q)===-1&&(x(q),q=""),$();let K=d();_(q,U,z,"",K);continue}let k=N??l("ESCAPED_CHAR");if(k){x(k);continue}if(l("OPEN")){let q=m(),K=l("NAME"),G=l("REGEX");!K&&!G&&(G=l("ASTERISK"));let C=m();p("CLOSE");let E=d();_(q,K,G,C,E);continue}$(),p("END")}return o}i(ov,"D");function rt(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}i(rt,"S");function tv(t){return t&&t.ignoreCase?"ui":"u"}i(tv,"X");function Ck(t,e,r){return iv(ov(t,r),e,r)}i(Ck,"Z");function Zr(t){switch(t){case 0:return"*";case 1:return"?";case 2:return"+";case 3:return""}}i(Zr,"k");function iv(t,e,r={}){r.delimiter??="/#?",r.prefixes??="./",r.sensitive??=!1,r.strict??=!1,r.end??=!0,r.start??=!0,r.endsWith="";let n=r.start?"^":"";for(let u of t){if(u.type===3){u.modifier===3?n+=rt(u.value):n+=`(?:${rt(u.value)})${Zr(u.modifier)}`;continue}e&&e.push(u.name);let c=`[^${rt(r.delimiter)}]+?`,l=u.value;if(u.type===1?l=c:u.type===0&&(l=Cp),!u.prefix.length&&!u.suffix.length){u.modifier===3||u.modifier===1?n+=`(${l})${Zr(u.modifier)}`:n+=`((?:${l})${Zr(u.modifier)})`;continue}if(u.modifier===3||u.modifier===1){n+=`(?:${rt(u.prefix)}(${l})${rt(u.suffix)})`,n+=Zr(u.modifier);continue}n+=`(?:${rt(u.prefix)}`,n+=`((?:${l})(?:`,n+=rt(u.suffix),n+=rt(u.prefix),n+=`(?:${l}))*)${rt(u.suffix)})`,u.modifier===0&&(n+="?")}let o=`[${rt(r.endsWith)}]|$`,s=`[${rt(r.delimiter)}]`;if(r.end)return r.strict||(n+=`${s}?`),r.endsWith.length?n+=`(?=${o})`:n+="$",new RegExp(n,tv(r));r.strict||(n+=`(?:${s}(?=${o}))?`);let a=!1;if(t.length){let u=t[t.length-1];u.type===3&&u.modifier===3&&(a=r.delimiter.indexOf(u)>-1)}return a||(n+=`(?=${s}|${o})`),new RegExp(n,tv(r))}i(iv,"F");var Gt={delimiter:"",prefixes:"",sensitive:!0,strict:!0},Ak={delimiter:".",prefixes:"",sensitive:!0,strict:!0},Nk={delimiter:"/",prefixes:"/",sensitive:!0,strict:!0};function Lk(t,e){return t.length?t[0]==="/"?!0:!e||t.length<2?!1:(t[0]=="\\"||t[0]=="{")&&t[1]=="/":!1}i(Lk,"J");function sv(t,e){return t.startsWith(e)?t.substring(e.length,t.length):t}i(sv,"Q");function zk(t,e){return t.endsWith(e)?t.substr(0,t.length-e.length):t}i(zk,"Ee");function av(t){return!t||t.length<2?!1:t[0]==="["||(t[0]==="\\"||t[0]==="{")&&t[1]==="["}i(av,"W");var uv=["ftp","file","http","https","ws","wss"];function cv(t){if(!t)return!0;for(let e of uv)if(t.test(e))return!0;return!1}i(cv,"N");function Uk(t,e){if(t=sv(t,"#"),e||t==="")return t;let r=new URL("https://example.com");return r.hash=t,r.hash?r.hash.substring(1,r.hash.length):""}i(Uk,"te");function Dk(t,e){if(t=sv(t,"?"),e||t==="")return t;let r=new URL("https://example.com");return r.search=t,r.search?r.search.substring(1,r.search.length):""}i(Dk,"re");function jk(t,e){return e||t===""?t:av(t)?pv(t):dv(t)}i(jk,"ne");function Zk(t,e){if(e||t==="")return t;let r=new URL("https://example.com");return r.password=t,r.password}i(Zk,"se");function Mk(t,e){if(e||t==="")return t;let r=new URL("https://example.com");return r.username=t,r.username}i(Mk,"ie");function qk(t,e,r){if(r||t==="")return t;if(e&&!uv.includes(e))return new URL(`${e}:${t}`).pathname;let n=t[0]=="/";return t=new URL(n?t:"/-"+t,"https://example.com").pathname,n||(t=t.substring(2,t.length)),t}i(qk,"ae");function Hk(t,e,r){return lv(e)===t&&(t=""),r||t===""?t:mv(t)}i(Hk,"oe");function Fk(t,e){return t=zk(t,":"),e||t===""?t:Ap(t)}i(Fk,"ce");function lv(t){switch(t){case"ws":case"http":return"80";case"wws":case"https":return"443";case"ftp":return"21";default:return""}}i(lv,"_");function Ap(t){if(t==="")return t;if(/^[-+.A-Za-z0-9]*$/.test(t))return t.toLowerCase();throw new TypeError(`Invalid protocol '${t}'.`)}i(Ap,"y");function Bk(t){if(t==="")return t;let e=new URL("https://example.com");return e.username=t,e.username}i(Bk,"le");function Vk(t){if(t==="")return t;let e=new URL("https://example.com");return e.password=t,e.password}i(Vk,"fe");function dv(t){if(t==="")return t;if(/[\t\n\r #%/:<>?@[\]^\\|]/g.test(t))throw new TypeError(`Invalid hostname '${t}'`);let e=new URL("https://example.com");return e.hostname=t,e.hostname}i(dv,"z");function pv(t){if(t==="")return t;if(/[^0-9a-fA-F[\]:]/g.test(t))throw new TypeError(`Invalid IPv6 hostname '${t}'`);return t.toLowerCase()}i(pv,"j");function mv(t){if(t===""||/^[0-9]*$/.test(t)&&parseInt(t)<=65535)return t;throw new TypeError(`Invalid port '${t}'.`)}i(mv,"K");function Gk(t){if(t==="")return t;let e=new URL("https://example.com");return e.pathname=t[0]!=="/"?"/-"+t:t,t[0]!=="/"?e.pathname.substring(2,e.pathname.length):e.pathname}i(Gk,"he");function Jk(t){return t===""?t:new URL(`data:${t}`).pathname}i(Jk,"ue");function Wk(t){if(t==="")return t;let e=new URL("https://example.com");return e.search=t,e.search.substring(1,e.search.length)}i(Wk,"de");function Kk(t){if(t==="")return t;let e=new URL("https://example.com");return e.hash=t,e.hash.substring(1,e.hash.length)}i(Kk,"pe");var Qk=class{static{i(this,"H")}#e;#t=[];#n={};#r=0;#o=1;#i=0;#s=0;#u=0;#c=0;#l=!1;constructor(t){this.#e=t}get result(){return this.#n}parse(){for(this.#t=nv(this.#e,!0);this.#r<this.#t.length;this.#r+=this.#o){if(this.#o=1,this.#t[this.#r].type==="END"){if(this.#s===0){this.#v(),this.#m()?this.#a(9,1):this.#f()?this.#a(8,1):this.#a(7,0);continue}else if(this.#s===2){this.#g(5);continue}this.#a(10,0);break}if(this.#u>0)if(this.#_())this.#u-=1;else continue;if(this.#S()){this.#u+=1;continue}switch(this.#s){case 0:this.#w()&&this.#g(1);break;case 1:if(this.#w()){this.#$();let t=7,e=1;this.#R()?(t=2,e=3):this.#l&&(t=2),this.#a(t,e)}break;case 2:this.#y()?this.#g(3):(this.#b()||this.#f()||this.#m())&&this.#g(5);break;case 3:this.#P()?this.#a(4,1):this.#y()&&this.#a(5,1);break;case 4:this.#y()&&this.#a(5,1);break;case 5:this.#k()?this.#c+=1:this.#E()&&(this.#c-=1),this.#I()&&!this.#c?this.#a(6,1):this.#b()?this.#a(7,0):this.#f()?this.#a(8,1):this.#m()&&this.#a(9,1);break;case 6:this.#b()?this.#a(7,0):this.#f()?this.#a(8,1):this.#m()&&this.#a(9,1);break;case 7:this.#f()?this.#a(8,1):this.#m()&&this.#a(9,1);break;case 8:this.#m()&&this.#a(9,1);break;case 9:break;case 10:break}}this.#n.hostname!==void 0&&this.#n.port===void 0&&(this.#n.port="")}#a(t,e){switch(this.#s){case 0:break;case 1:this.#n.protocol=this.#p();break;case 2:break;case 3:this.#n.username=this.#p();break;case 4:this.#n.password=this.#p();break;case 5:this.#n.hostname=this.#p();break;case 6:this.#n.port=this.#p();break;case 7:this.#n.pathname=this.#p();break;case 8:this.#n.search=this.#p();break;case 9:this.#n.hash=this.#p();break;case 10:break}this.#s!==0&&t!==10&&([1,2,3,4].includes(this.#s)&&[6,7,8,9].includes(t)&&(this.#n.hostname??=""),[1,2,3,4,5,6].includes(this.#s)&&[8,9].includes(t)&&(this.#n.pathname??=this.#l?"/":""),[1,2,3,4,5,6,7].includes(this.#s)&&t===9&&(this.#n.search??="")),this.#x(t,e)}#x(t,e){this.#s=t,this.#i=this.#r+e,this.#r+=e,this.#o=0}#v(){this.#r=this.#i,this.#o=0}#g(t){this.#v(),this.#s=t}#h(t){return t<0&&(t=this.#t.length-t),t<this.#t.length?this.#t[t]:this.#t[this.#t.length-1]}#d(t,e){let r=this.#h(t);return r.value===e&&(r.type==="CHAR"||r.type==="ESCAPED_CHAR"||r.type==="INVALID_CHAR")}#w(){return this.#d(this.#r,":")}#R(){return this.#d(this.#r+1,"/")&&this.#d(this.#r+2,"/")}#y(){return this.#d(this.#r,"@")}#P(){return this.#d(this.#r,":")}#I(){return this.#d(this.#r,":")}#b(){return this.#d(this.#r,"/")}#f(){if(this.#d(this.#r,"?"))return!0;if(this.#t[this.#r].value!=="?")return!1;let t=this.#h(this.#r-1);return t.type!=="NAME"&&t.type!=="REGEX"&&t.type!=="CLOSE"&&t.type!=="ASTERISK"}#m(){return this.#d(this.#r,"#")}#S(){return this.#t[this.#r].type=="OPEN"}#_(){return this.#t[this.#r].type=="CLOSE"}#k(){return this.#d(this.#r,"[")}#E(){return this.#d(this.#r,"]")}#p(){let t=this.#t[this.#r],e=this.#h(this.#i).index;return this.#e.substring(e,t.index)}#$(){let t={};Object.assign(t,Gt),t.encodePart=Ap;let e=Ck(this.#p(),void 0,t);this.#l=cv(e)}},Op=["protocol","username","password","hostname","port","pathname","search","hash"],Vt="*";function rv(t,e){if(typeof t!="string")throw new TypeError("parameter 1 is not of type 'string'.");let r=new URL(t,e);return{protocol:r.protocol.substring(0,r.protocol.length-1),username:r.username,password:r.password,hostname:r.hostname,port:r.port,pathname:r.pathname,search:r.search!==""?r.search.substring(1,r.search.length):void 0,hash:r.hash!==""?r.hash.substring(1,r.hash.length):void 0}}i(rv,"ge");function Ct(t,e){return e?fo(t):t}i(Ct,"b");function mo(t,e,r){let n;if(typeof e.baseURL=="string")try{n=new URL(e.baseURL),e.protocol===void 0&&(t.protocol=Ct(n.protocol.substring(0,n.protocol.length-1),r)),!r&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&(t.username=Ct(n.username,r)),!r&&e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.username===void 0&&e.password===void 0&&(t.password=Ct(n.password,r)),e.protocol===void 0&&e.hostname===void 0&&(t.hostname=Ct(n.hostname,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&(t.port=Ct(n.port,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&(t.pathname=Ct(n.pathname,r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&(t.search=Ct(n.search.substring(1,n.search.length),r)),e.protocol===void 0&&e.hostname===void 0&&e.port===void 0&&e.pathname===void 0&&e.search===void 0&&e.hash===void 0&&(t.hash=Ct(n.hash.substring(1,n.hash.length),r))}catch{throw new TypeError(`invalid baseURL '${e.baseURL}'.`)}if(typeof e.protocol=="string"&&(t.protocol=Fk(e.protocol,r)),typeof e.username=="string"&&(t.username=Mk(e.username,r)),typeof e.password=="string"&&(t.password=Zk(e.password,r)),typeof e.hostname=="string"&&(t.hostname=jk(e.hostname,r)),typeof e.port=="string"&&(t.port=Hk(e.port,t.protocol,r)),typeof e.pathname=="string"){if(t.pathname=e.pathname,n&&!Lk(t.pathname,r)){let o=n.pathname.lastIndexOf("/");o>=0&&(t.pathname=Ct(n.pathname.substring(0,o+1),r)+t.pathname)}t.pathname=qk(t.pathname,t.protocol,r)}return typeof e.search=="string"&&(t.search=Dk(e.search,r)),typeof e.hash=="string"&&(t.hash=Uk(e.hash,r)),t}i(mo,"w");function fo(t){return t.replace(/([+*?:{}()\\])/g,"\\$1")}i(fo,"C");function Xk(t){return t.replace(/([.+*?^${}()[\]|/\\])/g,"\\$1")}i(Xk,"Oe");function Yk(t,e){e.delimiter??="/#?",e.prefixes??="./",e.sensitive??=!1,e.strict??=!1,e.end??=!0,e.start??=!0,e.endsWith="";let r=".*",n=`[^${Xk(e.delimiter)}]+?`,o=/[$_\u200C\u200D\p{ID_Continue}]/u,s="";for(let a=0;a<t.length;++a){let u=t[a];if(u.type===3){if(u.modifier===3){s+=fo(u.value);continue}s+=`{${fo(u.value)}}${Zr(u.modifier)}`;continue}let c=u.hasCustomName(),l=!!u.suffix.length||!!u.prefix.length&&(u.prefix.length!==1||!e.prefixes.includes(u.prefix)),d=a>0?t[a-1]:null,p=a<t.length-1?t[a+1]:null;if(!l&&c&&u.type===1&&u.modifier===3&&p&&!p.prefix.length&&!p.suffix.length)if(p.type===3){let m=p.value.length>0?p.value[0]:"";l=o.test(m)}else l=!p.hasCustomName();if(!l&&!u.prefix.length&&d&&d.type===3){let m=d.value[d.value.length-1];l=e.prefixes.includes(m)}l&&(s+="{"),s+=fo(u.prefix),c&&(s+=`:${u.name}`),u.type===2?s+=`(${u.value})`:u.type===1?c||(s+=`(${n})`):u.type===0&&(!c&&(!d||d.type===3||d.modifier!==3||l||u.prefix!=="")?s+="*":s+=`(${r})`),u.type===1&&c&&u.suffix.length&&o.test(u.suffix[0])&&(s+="\\"),s+=fo(u.suffix),l&&(s+="}"),u.modifier!==3&&(s+=Zr(u.modifier))}return s}i(Yk,"ke");var ws=class{static{i(this,"me")}#e;#t={};#n={};#r={};#o={};#i=!1;constructor(t={},e,r){try{let n;if(typeof e=="string"?n=e:r=e,typeof t=="string"){let u=new Qk(t);if(u.parse(),t=u.result,n===void 0&&typeof t.protocol!="string")throw new TypeError("A base URL must be provided for a relative constructor string.");t.baseURL=n}else{if(!t||typeof t!="object")throw new TypeError("parameter 1 is not of type 'string' and cannot convert to dictionary.");if(n)throw new TypeError("parameter 1 is not of type 'string'.")}typeof r>"u"&&(r={ignoreCase:!1});let o={ignoreCase:r.ignoreCase===!0},s={pathname:Vt,protocol:Vt,username:Vt,password:Vt,hostname:Vt,port:Vt,search:Vt,hash:Vt};this.#e=mo(s,t,!0),lv(this.#e.protocol)===this.#e.port&&(this.#e.port="");let a;for(a of Op){if(!(a in this.#e))continue;let u={},c=this.#e[a];switch(this.#n[a]=[],a){case"protocol":Object.assign(u,Gt),u.encodePart=Ap;break;case"username":Object.assign(u,Gt),u.encodePart=Bk;break;case"password":Object.assign(u,Gt),u.encodePart=Vk;break;case"hostname":Object.assign(u,Ak),av(c)?u.encodePart=pv:u.encodePart=dv;break;case"port":Object.assign(u,Gt),u.encodePart=mv;break;case"pathname":cv(this.#t.protocol)?(Object.assign(u,Nk,o),u.encodePart=Gk):(Object.assign(u,Gt,o),u.encodePart=Jk);break;case"search":Object.assign(u,Gt,o),u.encodePart=Wk;break;case"hash":Object.assign(u,Gt,o),u.encodePart=Kk;break}try{this.#o[a]=ov(c,u),this.#t[a]=iv(this.#o[a],this.#n[a],u),this.#r[a]=Yk(this.#o[a],u),this.#i=this.#i||this.#o[a].some(l=>l.type===2)}catch{throw new TypeError(`invalid ${a} pattern '${this.#e[a]}'.`)}}}catch(n){throw new TypeError(`Failed to construct 'URLPattern': ${n.message}`)}}test(t={},e){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return!1;try{typeof t=="object"?r=mo(r,t,!1):r=mo(r,rv(t,e),!1)}catch{return!1}let n;for(n of Op)if(!this.#t[n].exec(r[n]))return!1;return!0}exec(t={},e){let r={pathname:"",protocol:"",username:"",password:"",hostname:"",port:"",search:"",hash:""};if(typeof t!="string"&&e)throw new TypeError("parameter 1 is not of type 'string'.");if(typeof t>"u")return;try{typeof t=="object"?r=mo(r,t,!1):r=mo(r,rv(t,e),!1)}catch{return null}let n={};e?n.inputs=[t,e]:n.inputs=[t];let o;for(o of Op){let s=this.#t[o].exec(r[o]);if(!s)return null;let a={};for(let[u,c]of this.#n[o].entries())if(typeof c=="string"||typeof c=="number"){let l=s[u+1];a[c]=l}n[o]={input:r[o]??"",groups:a}}return n}static compareComponent(t,e,r){let n=i((u,c)=>{for(let l of["type","modifier","prefix","value","suffix"]){if(u[l]<c[l])return-1;if(u[l]!==c[l])return 1}return 0},"o"),o=new go(3,"","","","",3),s=new go(0,"","","","",3),a=i((u,c)=>{let l=0;for(;l<Math.min(u.length,c.length);++l){let d=n(u[l],c[l]);if(d)return d}return u.length===c.length?0:n(u[l]??o,c[l]??o)},"s");return!e.#r[t]&&!r.#r[t]?0:e.#r[t]&&!r.#r[t]?a(e.#o[t],[s]):!e.#r[t]&&r.#r[t]?a([s],r.#o[t]):a(e.#o[t],r.#o[t])}get protocol(){return this.#r.protocol}get username(){return this.#r.username}get password(){return this.#r.password}get hostname(){return this.#r.hostname}get port(){return this.#r.port}get pathname(){return this.#r.pathname}get search(){return this.#r.search}get hash(){return this.#r.hash}get hasRegExpGroups(){return this.#i}};var xs=class{static{i(this,"UrlPatternBuilder")}pattern;pathParams={};searchParams=new URLSearchParams;expectedPathParams=new Set;seenPathParams=new Set;constructor(e){this.pattern=new ws({pathname:e});let r=/:(\w+)(\([^)]*\))?[*+?]?/g,n;for(;(n=r.exec(e))!==null;)this.expectedPathParams.add(n[1])}addParameter(e,r,n){let o=this.getParameterValue(e,r,n);if(o!=null)switch(e.in){case"path":if(!this.expectedPathParams.has(e.name))throw new y(`path parameter '${e.name}' missing from pattern '${this.pattern.pathname}'`);this.seenPathParams.add(e.name),this.addPathParameter(e.name,o);break;case"query":this.addQueryParameter(e.name,o);break;default:break}}getParameterValue(e,r,n){switch(e.in){case"path":return r?.[e.name];case"query":return n?.[e.name];default:return}}addPathParameter(e,r){this.pathParams[e]=String(r)}addQueryParameter(e,r){Array.isArray(r)?r.forEach(n=>{n!=null&&this.searchParams.append(e,String(n))}):typeof r=="object"&&r!==null?this.searchParams.append(e,JSON.stringify(r)):this.searchParams.append(e,String(r))}toString(){let e=[...this.expectedPathParams].filter(s=>!this.seenPathParams.has(s));if(e.length>0)throw new y(`missing path parameters in OpenAPI spec: ${e.join(", ")}`);let r=this.pattern.pathname.replace(/:(\w+)(\([^)]*\))?([*+?])?/g,(s,a)=>this.pathParams[a]?encodeURIComponent(this.pathParams[a]):s),n=this.cleanupUrlPatternSyntax(r),o=this.searchParams.toString();return o?`${n}?${o}`:n}cleanupUrlPatternSyntax(e){return e.replace(/\{\/\}\?/g,"").replace(/\{\/\}[*+]/g,"/").replace(/\{\/\}/g,"/").replace(/(\{[^}]*\})[?*+]/g,"$1")}};var Rs=class{constructor(e){this.routeData=e}static{i(this,"McpUrlBuilder")}build(e,r){let n=this.routeData.pathPattern?this.routeData.pathPattern:this.routeData.path,o=this.routeData.raw()?.parameters||[],s=new xs(n);for(let a of o)s.addParameter(a,e,r);return s.toString()}};Le();Le();Le();var Ps=class{static{i(this,"ZodFormatSchemaRegistry")}static formatter=new Map([["email",()=>g.email()],["uri",()=>g.url()],["url",()=>g.url()],["uuid",()=>g.uuid()],["date",()=>g.iso.date()],["date-time",()=>g.iso.datetime()],["time",()=>g.iso.time()],["ipv4",()=>g.ipv4()],["ipv6",()=>g.ipv6()],["int32",()=>g.int32()],["int64",()=>g.int64()],["float",()=>g.number()],["double",()=>g.number()]]);static get(e){return this.formatter.get(e)}static register(e,r){this.formatter.set(e,r)}},ho=class{static{i(this,"OpenApiToZodTranspiler")}static typeTranspilers=new Map([["string",this.transpileString.bind(this)],["number",this.transpileNumber.bind(this)],["integer",this.transpileInteger.bind(this)],["boolean",this.transpileBoolean.bind(this)],["array",this.transpileArray.bind(this)],["object",this.transpileObject.bind(this)],["null",this.transpileNull.bind(this)]]);static run(e,r){let n={path:[],definitions:{},visitedRefs:new Set,...r};return this.transpileSchema(e,n)}static transpileSchema(e,r){if(!e)return g.unknown();try{if("$ref"in e)return this.resolveReference(e.$ref,r);if(e.allOf)return this.transpileAllOf(e.allOf,r);if(e.oneOf)return this.transpileOneOf(e.oneOf,r);if(e.anyOf)return this.transpileAnyOf(e.anyOf,r);if(e.not)return this.transpileNot(e.not,r);let n=this.transpileByType(e,r);return n=this.applyCommonModifiers(n,e),n}catch(n){let o=r.path.join(".");throw new Error(`Failed to transpile schema at path "${o}": ${n.message}`)}}static transpileByType(e,r){let n=e.type;!n&&e.properties&&(n="object");let o=this.typeTranspilers.get(n||"unknown");return o?o(e,r):g.unknown()}static transpileString(e,r){if(e.enum)return g.enum(e.enum);let n=e.format?Ps.get(e.format):null,o=n?n():g.string();if(o instanceof g.ZodString){let s=o;return e.minLength!==void 0&&(s=s.min(e.minLength)),e.maxLength!==void 0&&(s=s.max(e.maxLength)),e.pattern&&(s=s.regex(new RegExp(e.pattern))),s}else e.minLength||e.maxLength||e.pattern;return o}static applyNumericConstraints(e,r,n){let o=e;if(r.minimum!==void 0&&(o=o.min(r.minimum)),r.maximum!==void 0&&(o=o.max(r.maximum)),r.exclusiveMinimum!==void 0){let s;if(typeof r.exclusiveMinimum=="number")s=r.exclusiveMinimum;else if(r.minimum!==void 0)s=r.minimum+Number.EPSILON;else throw new Error(`exclusiveMinimum requires minimum to be set at path "${n.path.join(".")}"`);o=o.gt(s)}if(r.exclusiveMaximum!==void 0){let s;if(typeof r.exclusiveMaximum=="number")s=r.exclusiveMaximum;else if(r.maximum!==void 0)s=r.maximum-Number.EPSILON;else throw new Error(`exclusiveMaximum requires maximum to be set at path "${n.path.join(".")}"`);o=o.lt(s)}return o}static transpileNumber(e,r){let n=g.number();return this.applyNumericConstraints(n,{...e,type:"number"},r)}static transpileInteger(e,r){let n=g.int();return this.applyNumericConstraints(n,{...e,type:"number"},r)}static transpileBoolean(e,r){return g.boolean()}static transpileArray(e,r){let n=e.items?this.transpileSchema(e.items,{...r,path:[...r.path,"items"]}):g.unknown(),o=g.array(n);return e.minItems!==void 0&&(o=o.min(e.minItems)),e.maxItems!==void 0&&(o=o.max(e.maxItems)),e.uniqueItems&&(o=o.refine(s=>new Set(s).size===s.length,{message:"Array must contain unique items"})),o}static transpileObject(e,r){let n;if(e.properties){let o={},s=new Set(e.required||[]);for(let[u,c]of Object.entries(e.properties)){let l={...r,path:[...r.path,u]},d=this.transpileSchema(c,l);s.has(u)||(d=d.optional()),o[u]=d}let a=g.object(o);e.additionalProperties===!1?a=a.strict():(e.additionalProperties,a=a.passthrough()),n=a}else if(e.additionalProperties===!1)n=g.object({}).strict();else if(typeof e.additionalProperties=="object"){let o=this.transpileSchema(e.additionalProperties,r);n=g.record(g.string(),o)}else n=g.unknown();return(e.minProperties!==void 0||e.maxProperties!==void 0)&&(n=n.refine(o=>{let s=Object.keys(o).length;return!(e.minProperties!==void 0&&s<e.minProperties||e.maxProperties!==void 0&&s>e.maxProperties)},{message:this.buildPropertyCountErrorMessage(e.minProperties,e.maxProperties)})),n}static buildPropertyCountErrorMessage(e,r){return e!==void 0&&r!==void 0?`Object must have between ${e} and ${r} properties`:e!==void 0?`Object must have at least ${e} properties`:`Object must have at most ${r} properties`}static transpileNull(e,r){return g.null()}static transpileAllOf(e,r){return e.map((o,s)=>this.transpileSchema(o,{...r,path:[...r.path,`allOf[${s}]`]})).reduce((o,s)=>o.and(s))}static transpileOneOf(e,r){let n=e.map((o,s)=>this.transpileSchema(o,{...r,path:[...r.path,`oneOf[${s}]`]}));return n.length===0?g.never():n.length===1?n[0]:g.union(n)}static transpileAnyOf(e,r){return this.transpileOneOf(e,r)}static transpileNot(e,r){let n=this.transpileSchema(e,{...r,path:[...r.path,"not"]});return g.unknown().refine(o=>!n.safeParse(o).success,{message:"Value must not match the schema"})}static resolveReference(e,r){if(r.visitedRefs?.has(e))return g.lazy(()=>this.resolveReference(e,r));r.visitedRefs?.add(e);let n=e.split("/");if(n[0]==="#"&&n[1]==="definitions"&&r.definitions){let o=r.definitions[n[2]];if(o)return this.transpileSchema(o,r)}throw new Error(`Unable to resolve reference: ${e}`)}static applyCommonModifiers(e,r){let n=e;return r.nullable&&(n=n.nullable()),r.default!==void 0&&(n=n.default(r.default)),r.description&&(n=n.describe(r.description)),r.examples&&r.examples.length>0&&(n=n.meta({examples:r.examples})),n}static registerTypeTranspiler(e,r){this.typeTranspilers.set(e,r)}static registerFormatSchema(e,r){Ps.register(e,r)}};var Is=class{constructor(e,r){this.routeData=e;this.contentType=r}static{i(this,"RequestBodySchemaBuilder")}build(){let e=this.routeData.raw()?.requestBody;if(!e?.content?.[this.contentType])return null;let r=e.content[this.contentType].schema;return r?ho.run(r):null}},Ss=class{constructor(e){this.parameters=e}static{i(this,"ParameterSchemaBuilder")}build(){if(this.parameters.length===0)return null;let e={};for(let r of this.parameters)e[r.name]=this.buildParameterSchema(r);return g.object(e)}buildParameterSchema(e){let r;e.schema?r=ho.run(e.schema):r=g.string(),e.required||(r=r.optional()),e.description&&(r=r.describe(e.description));let n=[];if(e.schema?.example!==void 0&&n.push(e.schema.example),e.schema?.examples!==void 0&&Array.isArray(e.schema.examples)&&n.push(...e.schema.examples),e.examples&&(Array.isArray(e.examples)?n.push(...e.examples):typeof e.examples=="object"&&Object.values(e.examples).forEach(o=>{o?.value!==void 0&&n.push(o.value)})),e.example!==void 0&&n.push(e.example),n.length>0){let o=[...new Set(n.map(s=>JSON.stringify(s)))].map(s=>JSON.parse(s));r=r.meta({examples:o})}return r}};var Np=class{static{i(this,"UniversalValidatorBuilder")}components={};withBody(e){return e&&(this.components.body=e),this}withQueryParams(e){return e&&(this.components.queryParams=e),this}withPathParams(e){return e&&(this.components.pathParams=e),this}withHeaders(e){return e&&(this.components.headers=e),this}build(){if(Object.keys(this.components).length===0)return this.buildEmptyValidator();let e=g.object(this.components),r=g.toJSONSchema(e);return new Bt(r,n=>{let o=e.safeParse(n);return o.success?{success:!0,data:n,errorData:null}:{success:!1,data:null,errorMessage:this.formatValidationErrors(o.error.issues),errorData:o.error}})}buildEmptyValidator(){let e={type:"object",properties:{},required:[],additionalProperties:!1};return new Bt(e,()=>({success:!0,data:{},errorData:null}))}formatValidationErrors(e){return e.map(r=>`${r.path.length>0?r.path.join("."):"root"}: ${r.message}`).join(", ")}},_s=class{static{i(this,"SchemaBuilderFactory")}static createRequestBodyBuilder(e,r){return new Is(e,r)}static createParameterBuilder(e,r){let n=r?e.filter(o=>o.in===r):e;return new Ss(n)}static createValidatorBuilder(e,r){let n=new Np,o=e.raw()?.parameters||[];if(r){let c=this.createRequestBodyBuilder(e,r);n.withBody(c.build())}let s=this.createParameterBuilder(o,"query");n.withQueryParams(s.build());let a=this.createParameterBuilder(o,"path");n.withPathParams(a.build());let u=this.createParameterBuilder(o,"header");return n.withHeaders(u.build()),n}};import{AsyncLocalStorage as eE}from"node:async_hooks";var Lp=new eE;function fv(t,e,r){return Lp.run({headers:t,zuploContext:e},r)}i(fv,"runWithInvokeContext");function ks(){return Lp.getStore()?.headers??{}}i(ks,"getInvokeHeaders");function gv(){let t=Lp.getStore();if(!t)throw new Error("No Zuplo context available in current execution context");return t.zuploContext}i(gv,"getInvokeContext");function hv(t){if(!t||typeof t!="object")throw new Error(`must be an object, got ${typeof t}`);let e=t;if(typeof e.name!="string"||e.name.trim()==="")throw new Error(`tool.name must be a string, got ${typeof e.name}`);if(typeof e.description!="string")throw new Error(`tool.description must be a string, got ${typeof e.description}`);if(typeof e.handler!="function")throw new Error(`tool.handler must be a function, got ${typeof e.handler}`);if(e.schema!==void 0&&typeof e.schema!="object")throw new Error(`tool.schema must be a Zod schema, got ${typeof e.schema}`);if(e.outputSchema!==void 0&&typeof e.outputSchema!="object")throw new Error(`tool.outputSchema must be a Zod schema, got ${typeof e.outputSchema}`)}i(hv,"checkMcpToolDefinition");var Es=class{static{i(this,"McpToolBuilder")}config={};name(e){return this.config.name=e,this}description(e){return this.config.description=e,this}schema(e){return this.config.schema=e,this}outSchema(e){return this.config.outSchema=e,this}handler(e){return this.config.handler=e,this}build(){if(!this.config.name||!this.config.description||!this.config.handler)throw new Error("Tool must have name, description, and handler defined");return{name:this.config.name,description:this.config.description,schema:this.config.schema,outputSchema:this.config.outSchema,handler:this.config.handler}}},zp=class{static{i(this,"McpCustomToolsSDK")}createTool(){return new Es}defineTool(e){return{name:e.name,description:e.description,schema:e.schema,outputSchema:e.outputSchema,handler:e.handler}}textResponse(e){return{content:[{type:"text",text:e}]}}jsonResponse(e){return{content:[{type:"text",text:JSON.stringify(e,null,2)}],structuredContent:e}}errorResponse(e){return{content:[{type:"text",text:`Error: ${e}`}],isError:!0}}imageResponse(e,r){return{content:[{type:"image",data:e,mimeType:r}]}}resourceResponse(e,r){return{content:[{type:"resource",uri:e,mimeType:r}]}}getInvokeHeaders(){return ks()}};var $s=class t{static{i(this,"ZuploMcpServer")}static instances=new Map;static async getInstance(e,r){let n=r.route?.path??"unknown-route",o=e.debugMode??!1,s=t.instances.get(n);if(s)o&&r.log.debug("MCP Server warm reuse",{routeKey:n});else{let a=Date.now();s=new t(e,r),s.registerToolsFromOptions(s.opts.openApiTools??[]),s.registerToolsFromFiles(s.opts.openApiFilePaths??[]);let u=s.opts.customTools&&s.opts.customTools.default?s.opts.customTools.default:[];if(await s.registerCustomTools(u),await s.transport.connect(),s.server.withTransport(s.transport),t.instances.set(n,s),o){let c=s.server.getTools(),l=c?c.size:0,d=Date.now()-a;r.log.debug("MCP Server cold start",{routeKey:n,toolCount:l,totalElapsedMs:d,debugMode:o,includeOutputSchema:s.includeOutputSchema,includeStructuredContent:s.includeStructuredContent})}}return s}transport;server;opts;context;includeOutputSchema;includeStructuredContent;debugMode;constructor(e,r){this.debugMode=e.debugMode??!1;let n;this.debugMode?n=r.log:n=new lo,this.context=r,this.opts=e,this.server=new bs({name:e.name??"Zuplo MCP Server",version:e.version??"0.0.0",logger:n}),this.transport=new vs({logger:n}),this.includeOutputSchema=e.includeOutputSchema??!1,this.includeStructuredContent=e.includeStructuredContent??!1}async handleRequest(e,r){let n=Date.now();try{let o=await e.clone().json().catch(()=>({}));if(this.debugMode&&r.log.debug("MCP Server request start",{method:o.method,requestId:o.id,routePath:r.route?.path}),this.debugMode&&o.method==="tools/list"){let u=this.server.getTools(),c=u?Array.from(u.keys()):[];r.log.debug("MCP Server list tools request",{toolCount:c.length,toolNames:c})}let s=await this.transport.handleRequest(e),a=Date.now()-n;if(this.debugMode){let u=await s.clone().json().catch(()=>({}));r.log.debug("MCP Server response complete",{status:s.status,requestMethod:o.method,requestId:o.id,totalElapsedMs:a,respData:u})}return s}catch(o){let s=Date.now()-n;return r.log.error("MCP server internal error",{elapsedMs:s,err:o}),new Response("Internal error",{status:500})}}generateToolNameFromSpec(e,r){let n=e.raw();if(n?.operationId)return`${n.operationId}`;let o=`${r}_${e.path}`.replace(/[^\w]/g,"_");return this.context.log.warn(`No operationId found for route ${r} ${e.path}. Using auto-generated name "${o}". To improve AI tool selection, add a descriptive operationId to your OpenAPI spec (e.g., "get_user_by_id" instead of "GET_/users/{id}")`),o}generateToolDescriptionFromSpec(e,r){let n=e.raw();return n?.description?n.description:n?.summary?n.summary:`Call ${r.toUpperCase()} ${e.path}`}registerToolsFromOptions(e){let r=new Set;for(let n of e){if(n.name){if(typeof n.name!="string"||n.name.trim()==="")throw new Error("MCP Tool configuration error: Tool name must be a non-empty string if provided.");if(r.has(n.name))throw new Error(`MCP Tool configuration error: Duplicate tool name "${n.name}". Tool names must be unique across all configured tools.`)}let o=this.getRouteDataForOptions(n);if(!o){let l=n.operationId?`operationId: "${n.operationId}"`:`path: "${n.path}"`;throw new Error(`MCP Tool configuration error: Could not find gateway route data for ${n.method.toUpperCase()} ${l}. Verify that the route exists in your OpenAPI specification and that the provided metadata matches OpenAPI specification data.`)}if(!o.handler){let l=n.operationId?`operationId: "${n.operationId}"`:`path: "${n.path}"`;throw new Error(`MCP Tool configuration error: Route ${n.method.toUpperCase()} ${l} has no handler configured. Ensure the route has a proper handler defined in your OpenAPI specification.`)}let s=n.name??this.generateToolNameFromSpec(o,n.method);if(r.has(s))throw new Error(`MCP Tool configuration error: Tool name conflict detected. The name "${s}" is already in use. Consider providing a unique 'name' in your tool configuration or ensure your operationIds are unique.`);r.add(s);let a=n.description??this.generateToolDescriptionFromSpec(o,n.method),u=n.includeOutputSchema??this.includeOutputSchema??!0,c=n.includeStructuredContent??this.includeStructuredContent??!0;this.registerToolsForMethod(o,n.method,s,a,u,c)}}registerToolsFromFiles(e){let r=new Set(e.map(s=>s.filePath)),n=new Set;for(let s of be.instance.routeData.routes){let a=s.metadata?.filepath;a&&r.has(a)&&(n.add(a),this.registerToolsForRawRoutedata(s,this.includeOutputSchema,this.includeStructuredContent))}let o=e.map(s=>s.filePath).filter(s=>!n.has(s));if(o.length>0)throw new Error(`MCP Tool configuration error: Could not find routes for the following file paths: ${o.join(", ")}. Verify that these OpenAPI files exist and are properly loaded in your Gateway configuration.`)}registerToolsForRawRoutedata(e,r,n){if(e.mcp?.enabled!==!1){if(!e)throw new Error("MCP Tool configuration error: Route data cannot be null or undefined.");if(!e.methods||e.methods.length===0)throw new Error(`MCP Tool configuration error: Route "${e.path}" has no HTTP methods defined. Ensure the route has at least one HTTP method (GET, POST, etc.) in your OpenAPI specification.`);if(!e.handler)throw new Error(`MCP Tool configuration error: Route "${e.path}" has no handler configured. Ensure the route has a proper handler defined in your OpenAPI specification.`);for(let o of e.methods){let s=this.generateToolNameFromSpec(e,o),a=this.generateToolDescriptionFromSpec(e,o);this.registerToolsForMethod(e,o,s,a,r,n)}}}registerToolsForMethod(e,r,n,o,s,a){if(e.handler?.export!=="mcpServerHandler")if(e.raw().requestBody?.content)for(let u of Object.keys(e.raw().requestBody?.content)){let l=Object.keys(e.raw().requestBody?.content).length>1?`${n}_${u.replace(/[^\w]/g,"_")}`:n;this.registerGenericToolSpec(l,o,e,r,u,s,a)}else this.registerGenericToolSpec(n,o,e,r,null,s,a)}registerGenericToolSpec(e,r,n,o,s,a,u){let c=this.buildUniversalValidator(n,s);if(!c)throw new Error(`MCP Tool registration error: Could not build parameter validator for ${o.toUpperCase()} ${n.path}. This may indicate an issue with the OpenAPI parameter definitions for this route.`);let l=a?this.extractOutputSchema(n):void 0;try{this.server.addTool({name:e,description:r,validator:c,...l&&{outputSchema:l},handler:i(async d=>{let p=gv(),m=Date.now();try{this.debugMode&&p.log.debug("MCP tool invoked",{toolName:e,operationId:n.raw()?.operationId,method:o,path:n.path,args:d});let f=this.buildToolUrl(n,d),h=this.buildToolRequest(o,s,d);this.debugMode&&p.log.debug("MCP tool downstream call",{toolName:e,url:f,method:o,headers:h.headers?Object.keys(h.headers).join(", "):"",bodyPreview:d.body});let w=Date.now(),x=await p.invokeRoute(f,h),$=Date.now()-w,_=await x.text(),N;if(u)try{N=JSON.parse(_)}catch(z){this.debugMode&&p.log.debug("MCP tool structuredContent JSON parse failed",{toolName:e,body:_,parseErr:z})}let U=Date.now()-m;return this.debugMode&&(x.ok?p.log.debug("MCP tool ok response",{toolName:e,operationId:n.raw()?.operationId,status:x.status,elapsedMs:U,downstreamElapsedMs:$}):p.log.debug("MCP tool 'isError' response",{toolName:e,operationId:n.raw()?.operationId,status:x.status,elapsedMs:U,downstreamElapsedMs:$,response:_})),{content:[{type:"text",text:_}],...N&&{structuredContent:N},isError:!x.ok}}catch(f){let h=Date.now()-m,w=f instanceof Error?`${f.name}: ${f.message}`:String(f);return p.log.error("MCP server tool invocation failed",{toolName:e,operationId:n.raw()?.operationId,method:o,path:n.path,elapsedMs:h,err:f}),{content:[{type:"text",text:`MCP tool call failed for tool '${e}': ${w}`}],isError:!0}}},"handler")}),this.debugMode&&this.context.log.debug("MCP tool registered",{toolName:e,method:o.toUpperCase(),path:n.path,operationId:n.raw()?.operationId,contentType:s||"none",includeOutputSchema:a,includeStructuredContent:u,hasValidator:!!c,hasOutputSchema:!!l})}catch(d){throw new Error(`Failed to add tool ${o} ${n.path}`,d)}}buildToolUrl(e,r){return new Rs(e).build(r.pathParams,r.queryParams)}buildToolRequest(e,r,n){let o=this.buildToolHeaders(e,r,n),s={method:e,headers:o};return this.shouldIncludeBody(e,r,n)&&(s.body=this.serializeBody(n.body,r)),s}buildToolHeaders(e,r,n){let o={...ks()};return n.headers&&Object.entries(n.headers).forEach(([s,a])=>{o[s.toLowerCase()]=a}),r&&n.body!==void 0&&(o["content-type"]=r),this.isBodyMethod(e||"")&&n.body!==void 0&&!o["content-type"]&&(o["content-type"]="application/json"),o}shouldIncludeBody(e,r,n){return n.body===void 0?!1:this.isBodyMethod(e)?!0:r!==null}isBodyMethod(e){return["POST","PUT","PATCH"].includes(e.toUpperCase())}serializeBody(e,r){return JSON.stringify(e)}buildUniversalValidator(e,r){try{let o=_s.createValidatorBuilder(e,r).build();return this.debugMode&&this.context.log.debug("MCP validator built successfully",{method:e.methods?.[0],path:e.path,contentType:r||"none",operationId:e.raw()?.operationId}),o}catch(n){let o=n instanceof Error?n.message:String(n);throw this.context.log.warn("MCP validator build failed",{method:e.methods?.[0],path:e.path,contentType:r||"none",operationId:e.raw()?.operationId,error:o}),n}}getRouteDataForOptions(e){let{routes:r}=be.instance.routeData,n=!!e.operationId,o=!!e.path;if(!n&&!o)throw new Error("MCP Tool configuration error: Either 'operationId' or 'path' must be provided in your tool specification.");return n?r.find(s=>s?.raw().operationId===e.operationId&&s?.methods?.some(a=>a.toUpperCase()===e.method.toUpperCase())):r.find(s=>s?.path===e.path&&s?.methods?.some(a=>a.toUpperCase()===e.method.toUpperCase()))}extractOutputSchema(e){try{let r=e.raw(),n=r?.responses;if(!n){this.context.log.warn("No responses found in OpenAPI spec for outputSchema",{path:e.path,operationId:r?.operationId});return}for(let o of Object.keys(n))if(o.startsWith("2")){let a=n[o]?.content;if(a){for(let u of["application/json","application/json; charset=utf-8"])if(a[u]?.schema){let c=a[u].schema;return this.debugMode&&this.context.log.debug("Output schema extracted successfully",{path:e.path,operationId:r?.operationId,statusCode:o,contentType:u,schemaKeys:c&&typeof c=="object"?Object.keys(c).join(", "):"none"}),c}}}this.debugMode&&this.context.log.debug("No OpenAPI spec 2xx responses fond for outputSchema",{path:e.path,operationId:r?.operationId,statusCodes:Object.keys(n).join(", ")});return}catch(r){this.context.log.warn("Failed to extract outputSchema",{path:e.path,operationId:e.raw()?.operationId,error:r instanceof Error?r.message:String(r),stack:r instanceof Error?r.stack:void 0});return}}async registerCustomTools(e){if(!e||e.length===0)return;if(!Array.isArray(e))throw new Error("customTools must be an array");let r=new Set;for(let n=0;n<e.length;n++){let o=e[n];try{hv(o)}catch(s){throw new Error(`customTools[${n}] is not a valid McpToolDefinition`,{cause:s})}if(r.has(o.name))throw new Error(`Duplicate custom tool name: ${o.name}`);r.add(o.name)}for(let n of e)await this.registerCustomTool(n);this.debugMode&&this.context.log.debug("Custom tools registered",{toolCount:e.length,toolNames:e.map(n=>n.name)})}async registerCustomTool(e){let{name:r,description:n,schema:o,outputSchema:s,handler:a}=e,u;if(o){let l=g.toJSONSchema(o);u=new Bt(l,d=>{let p=o.safeParse(d);return p.success?{success:!0,data:p.data,errorData:null}:{success:!1,data:null,errorData:p.error}})}else{let l={type:"object",properties:{},required:[],additionalProperties:!1};u=new Bt(l,()=>({success:!0,data:{},errorData:null}))}let c={name:r,description:n,validator:u,handler:i(async l=>{try{let d=await a(l,this.context);if(!d||typeof d!="object"||!Array.isArray(d.content))throw new Error("Handler must return an object with a content array");return d}catch(d){return this.context.log.error(`Custom tool '${r}' execution failed:`,d),{content:[{type:"text",text:`Tool execution failed: ${d instanceof Error?d.message:String(d)}`}],isError:!0}}},"handler")};if(s){let l=g.toJSONSchema(s);if(typeof l!="object"||l===null)throw new Error(`output schema for tool "${r}" must be an object`);c.outputSchema={...l,type:"object"}}this.server.addTool(c),this.debugMode&&this.context.log.debug("Custom tool registered",{name:r,description:n,hasSchema:!!o,hasOutputSchema:!!s})}};async function tE(t,e){if(b("handler.mcp-server"),e.route.methods.some(s=>s.toUpperCase()!=="POST"))throw new y(`Invalid route config: mcpServerHandler may only use POST. Route '${e.route.path}' declares methods: [${e.route.methods.join(", ")}]`);let r={};t.headers.forEach((s,a)=>{r[a]=s});let n=e.route?.handler?.options??{},o=await $s.getInstance(n,e);return fv(r,e,()=>o.handleRequest(t,e))}i(tE,"mcpServerHandler");function ut(t,e){let r={};for(let n in t){let o=t[n];Array.isArray(o)||(o=[o]);for(let s of o)if(s.param){if(n in e){let a=rE(n,e,s);a!==void 0&&yv(r,s.param,a)}else if(s&&s.required&&s.default!==void 0){let a=typeof s.default=="function"?s.default(e):s.default;yv(r,s.param,a)}}}return r}i(ut,"validateAndTransformRequest");function rE(t,e,r){let n=e[t];return r.transform&&(n=r.transform(e)),n===void 0&&r.default!==void 0&&(n=typeof r.default=="function"?r.default(e):r.default),typeof n=="number"&&(r.min!==void 0&&n<r.min&&(n=r.min),r.max!==void 0&&n>r.max&&(n=r.max)),n}i(rE,"getValue");function yv(t,e,r){if(r===void 0)return;let n=e.split("."),o=t;for(let s=0;s<n.length-1;s++){let a=n[s];o[a]||(o[a]={}),o=o[a]}o[n[n.length-1]]=r}i(yv,"setNestedProperty");var nE={model:{param:"model",required:!0,default:"gpt-4o-mini"},messages:{param:"messages",required:!0},temperature:{param:"temperature",default:1,min:0,max:2},top_p:{param:"top_p",default:1,min:0,max:1},n:{param:"n",default:1,min:1,max:128},stream:{param:"stream",default:!1},stop:{param:"stop"},max_tokens:{param:"max_tokens",min:0},presence_penalty:{param:"presence_penalty",default:0,min:-2,max:2},frequency_penalty:{param:"frequency_penalty",default:0,min:-2,max:2},logit_bias:{param:"logit_bias"},user:{param:"user"},seed:{param:"seed"},functions:{param:"functions"},function_call:{param:"function_call"},tools:{param:"tools"},tool_choice:{param:"tool_choice"},parallel_tool_calls:{param:"parallel_tool_calls"},response_format:{param:"response_format"},logprobs:{param:"logprobs",default:!1},top_logprobs:{param:"top_logprobs",min:0,max:20},max_completion_tokens:{param:"max_completion_tokens"},service_tier:{param:"service_tier"},stream_options:{param:"stream_options"}},oE={model:{param:"model",required:!0,default:"text-embedding-3-small"},input:{param:"input",required:!0},user:{param:"user"},dimensions:{param:"dimensions"},encoding_format:{param:"encoding_format",default:"float"}},Ts=class{static{i(this,"OpenAIProvider")}name="openai";async chatComplete(e,r){let n=ut(nE,e),o=await fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let a=await o.json();throw new Error(`OpenAI API error: ${a.error?.message||"Unknown error"}`)}return{...await o.json(),provider:"openai"}}async embed(e,r){let n=ut(oE,e),o=await fetch("https://api.openai.com/v1/embeddings",{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let a=await o.json();throw new Error(`OpenAI API error: ${a.error?.message||"Unknown error"}`)}return{...await o.json(),provider:"openai"}}};var iE={model:{param:"model",required:!0,default:"claude-3-5-sonnet-20241022"},messages:[{param:"messages",required:!0,transform:i(t=>t.messages.filter(r=>r.role!=="system").map(r=>({role:r.role==="assistant"?"assistant":"user",content:r.content})),"transform")},{param:"system",required:!1,transform:i(t=>{let r=t.messages.filter(n=>n.role==="system");if(r.length!==0)return r.map(n=>n.content).join(`
@@ -22,4 +22,4 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{b as e,c as t,e as a,f as o,g as r,h as i,i as n}from"../chunk-ABYPZMH4.js";import"../chunk-SSAQ7DDU.js";export{o as getIdForParameterSchema,i as getIdForRefSchema,r as getIdForRequestBodySchema,a as getRawOperationDataIdentifierName,e as isRestrictedEnvVariableName,t as isZuploReadableEnvVariableName,n as sanitizedIdentifierName};
25
+ import{b as e,c as t,e as a,f as o,g as r,h as i,i as n}from"../chunk-ZI6BEEZC.js";import"../chunk-6JMEGIXE.js";export{o as getIdForParameterSchema,i as getIdForRefSchema,r as getIdForRequestBodySchema,a as getRawOperationDataIdentifierName,e as isRestrictedEnvVariableName,t as isZuploReadableEnvVariableName,n as sanitizedIdentifierName};
@@ -22,4 +22,4 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as p}from"../chunk-7X7Y6YCS.js";import{Z as n,a as t}from"../chunk-SSAQ7DDU.js";function g(u={request:new Request("https://api.example.com")}){let e=[];function o(i){e.push(Promise.resolve(i))}return t(o,"waitUntil"),{context:new s({event:{waitUntil:o},route:u.route}),invokeResponse:t(async()=>{await Promise.all(e)},"invokeResponse")}}t(g,"createMockContext");var a={path:"/",methods:["GET"],handler:{module:{},export:"default"},raw:t(()=>({}),"raw")},s=class extends EventTarget{static{t(this,"MockZuploContext")}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;analyticsContext;constructor({event:e,route:o=a,parentContext:r}){super(),this.requestId=crypto.randomUUID(),this.contextId=crypto.randomUUID(),this.log={info:n.console.info,log:n.console.log,debug:n.console.debug,warn:n.console.warn,error:n.console.error},this.custom={},this.route=o,this.incomingRequestProperties={asn:1234,asOrganization:"ORGANIZATION",city:"Seattle",region:"Washington",regionCode:"WA",colo:"SEA",continent:"NA",country:"US",postalCode:"98004",metroCode:"SEA",latitude:void 0,longitude:void 0,timezone:void 0,httpProtocol:void 0},this.parentContext=r,this.#e=e,this.analyticsContext=new p(this.requestId)}waitUntil(e){this.#e.waitUntil(e)}invokeInboundPolicy(e,o){throw new Error("Not implemented")}invokeOutboundPolicy(e,o,r){throw new Error("Not implemented")}invokeRoute(e,o){throw new Error("Not implemented")}addResponseSendingHook(e){throw new Error("Not implemented")}addResponseSendingFinalHook(e){throw new Error("Not implemented")}addEventListener(e,o,r){let l=t(i=>{try{typeof o=="function"?o(i):o.handleEvent(i)}catch(d){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),d}},"wrapped");super.addEventListener(e,l,r)}};export{s as MockZuploContext,g as createMockContext};
25
+ import{a as p}from"../chunk-XGTJ3NUE.js";import{Z as n,a as t}from"../chunk-6JMEGIXE.js";function g(u={request:new Request("https://api.example.com")}){let e=[];function o(i){e.push(Promise.resolve(i))}return t(o,"waitUntil"),{context:new s({event:{waitUntil:o},route:u.route}),invokeResponse:t(async()=>{await Promise.all(e)},"invokeResponse")}}t(g,"createMockContext");var a={path:"/",methods:["GET"],handler:{module:{},export:"default"},raw:t(()=>({}),"raw")},s=class extends EventTarget{static{t(this,"MockZuploContext")}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;analyticsContext;constructor({event:e,route:o=a,parentContext:r}){super(),this.requestId=crypto.randomUUID(),this.contextId=crypto.randomUUID(),this.log={info:n.console.info,log:n.console.log,debug:n.console.debug,warn:n.console.warn,error:n.console.error},this.custom={},this.route=o,this.incomingRequestProperties={asn:1234,asOrganization:"ORGANIZATION",city:"Seattle",region:"Washington",regionCode:"WA",colo:"SEA",continent:"NA",country:"US",postalCode:"98004",metroCode:"SEA",latitude:void 0,longitude:void 0,timezone:void 0,httpProtocol:void 0},this.parentContext=r,this.#e=e,this.analyticsContext=new p(this.requestId)}waitUntil(e){this.#e.waitUntil(e)}invokeInboundPolicy(e,o){throw new Error("Not implemented")}invokeOutboundPolicy(e,o,r){throw new Error("Not implemented")}invokeRoute(e,o){throw new Error("Not implemented")}addResponseSendingHook(e){throw new Error("Not implemented")}addResponseSendingFinalHook(e){throw new Error("Not implemented")}addEventListener(e,o,r){let l=t(i=>{try{typeof o=="function"?o(i):o.handleEvent(i)}catch(d){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),d}},"wrapped");super.addEventListener(e,l,r)}};export{s as MockZuploContext,g as createMockContext};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
3
  "type": "module",
4
- "version": "6.59.7",
4
+ "version": "6.59.8",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {