@zuplo/runtime 6.51.33 → 6.51.35
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/esm/index.js +16 -16
- package/package.json +1 -1
package/out/esm/index.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a as y,b as bt,e as Se,f as Kl,g as Ao,h as _o,i as Ql,j as Yl}from"./chunk-TPMH5PF5.js";import{a as s,b as Wl,c as Jl}from"./chunk-PPV7V43C.js";var Mc=Wl(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.parse=Hd;Gr.serialize=Fd;var Md=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Dd=/^[\u0021-\u003A\u003C-\u007E]*$/,Zd=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,qd=/^[\u0020-\u003A\u003D-\u007E]*$/,$d=Object.prototype.toString,Ud=(()=>{let n=s(function(){},"C");return n.prototype=Object.create(null),n})();function Hd(n,e){let t=new Ud,r=n.length;if(r<2)return t;let o=e?.decode||jd,i=0;do{let a=n.indexOf("=",i);if(a===-1)break;let c=n.indexOf(";",i),u=c===-1?r:c;if(a>u){i=n.lastIndexOf(";",a-1)+1;continue}let l=Lc(n,i,a),d=Nc(n,a,l),p=n.slice(l,d);if(t[p]===void 0){let m=Lc(n,a+1,u),h=Nc(n,u,m),
|
|
25
|
+
import{a as y,b as bt,e as Se,f as Kl,g as Ao,h as _o,i as Ql,j as Yl}from"./chunk-TPMH5PF5.js";import{a as s,b as Wl,c as Jl}from"./chunk-PPV7V43C.js";var Mc=Wl(Gr=>{"use strict";Object.defineProperty(Gr,"__esModule",{value:!0});Gr.parse=Hd;Gr.serialize=Fd;var Md=/^[\u0021-\u003A\u003C\u003E-\u007E]+$/,Dd=/^[\u0021-\u003A\u003C-\u007E]*$/,Zd=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,qd=/^[\u0020-\u003A\u003D-\u007E]*$/,$d=Object.prototype.toString,Ud=(()=>{let n=s(function(){},"C");return n.prototype=Object.create(null),n})();function Hd(n,e){let t=new Ud,r=n.length;if(r<2)return t;let o=e?.decode||jd,i=0;do{let a=n.indexOf("=",i);if(a===-1)break;let c=n.indexOf(";",i),u=c===-1?r:c;if(a>u){i=n.lastIndexOf(";",a-1)+1;continue}let l=Lc(n,i,a),d=Nc(n,a,l),p=n.slice(l,d);if(t[p]===void 0){let m=Lc(n,a+1,u),h=Nc(n,u,m),w=o(n.slice(m,h));t[p]=w}i=u+1}while(i<r);return t}s(Hd,"parse");function Lc(n,e,t){do{let r=n.charCodeAt(e);if(r!==32&&r!==9)return e}while(++e<t);return t}s(Lc,"startIndex");function Nc(n,e,t){for(;e>t;){let r=n.charCodeAt(--e);if(r!==32&&r!==9)return e+1}return t}s(Nc,"endIndex");function Fd(n,e,t){let r=t?.encode||encodeURIComponent;if(!Md.test(n))throw new TypeError(`argument name is invalid: ${n}`);let o=r(e);if(!Dd.test(o))throw new TypeError(`argument val is invalid: ${e}`);let i=n+"="+o;if(!t)return i;if(t.maxAge!==void 0){if(!Number.isInteger(t.maxAge))throw new TypeError(`option maxAge is invalid: ${t.maxAge}`);i+="; Max-Age="+t.maxAge}if(t.domain){if(!Zd.test(t.domain))throw new TypeError(`option domain is invalid: ${t.domain}`);i+="; Domain="+t.domain}if(t.path){if(!qd.test(t.path))throw new TypeError(`option path is invalid: ${t.path}`);i+="; Path="+t.path}if(t.expires){if(!zd(t.expires)||!Number.isFinite(t.expires.valueOf()))throw new TypeError(`option expires is invalid: ${t.expires}`);i+="; Expires="+t.expires.toUTCString()}if(t.httpOnly&&(i+="; HttpOnly"),t.secure&&(i+="; Secure"),t.partitioned&&(i+="; Partitioned"),t.priority)switch(typeof t.priority=="string"?t.priority.toLowerCase():void 0){case"low":i+="; Priority=Low";break;case"medium":i+="; Priority=Medium";break;case"high":i+="; Priority=High";break;default:throw new TypeError(`option priority is invalid: ${t.priority}`)}if(t.sameSite)switch(typeof t.sameSite=="string"?t.sameSite.toLowerCase():t.sameSite){case!0:case"strict":i+="; SameSite=Strict";break;case"lax":i+="; SameSite=Lax";break;case"none":i+="; SameSite=None";break;default:throw new TypeError(`option sameSite is invalid: ${t.sameSite}`)}return i}s(Fd,"serialize");function jd(n){if(n.indexOf("%")===-1)return n;try{return decodeURIComponent(n)}catch{return n}}s(jd,"decode");function zd(n){return $d.call(n)==="[object Date]"}s(zd,"isDate")});var Xl=!1;function on(n,e){return{open:`\x1B[${n.join(";")}m`,close:`\x1B[${e}m`,regexp:new RegExp(`\\x1b\\[${e}m`,"g")}}s(on,"code");function sn(n,e){return Xl?`${e.open}${n.replace(e.regexp,e.open)}${e.close}`:n}s(sn,"run");function ed(n){return sn(n,on([31],39))}s(ed,"red");function td(n){return sn(n,on([32],39))}s(td,"green");function nd(n){return sn(n,on([33],39))}s(nd,"yellow");function rd(n){return sn(n,on([34],39))}s(rd,"blue");function od(n){return sn(n,on([35],39))}s(od,"magenta");function id(n){return sn(n,on([36],39))}s(id,"cyan");var xh=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 La=[ed,td,nd,rd,od,id];function sd(n){let e=0,t=n.length,r=0;if(t>0)for(;r<t;)e=(e<<5)-e+n.charCodeAt(r++)|0;return e}s(sd,"hashCode");function Na(n){let e=Math.abs(sd(n));return La[e%La.length]}s(Na,"generateColor");function Ma(n,e,...t){let r=0,o=t.length,i=String(e).replace(/%[sdjoO%]/g,a=>{if(a==="%%")return"%";if(r>=o)return a;switch(a){case"%s":return String(t[r++]);case"%d":return Number(t[r++]).toString();case"%o":return n(t[r++]).split(`
|
|
26
26
|
`).map(c=>c.trim()).join(" ");case"%O":return n(t[r++]);case"%j":try{return JSON.stringify(t[r++])}catch{return"[Circular]"}default:return a}});for(let a of t.splice(r))a===null||!(typeof a=="object"&&a!==null)?i+=" "+a:i+=" "+n(a);return i}s(Ma,"format");function wt(n,e,t,r){let o={seen:[],stylize:ad,showHidden:e??!1,depth:t??2,colors:r??!1,customInspect:!0};return o.colors&&(o.stylize=ud),Pr(o,n,o.depth)}s(wt,"inspect");wt.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]};wt.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function ad(n,e){return n}s(ad,"stylizeNoColor");function cd(n){return typeof n=="boolean"}s(cd,"isBoolean");function Za(n){return n===void 0}s(Za,"isUndefined");function ud(n,e){let t=wt.styles[e];return t?"\x1B["+wt.colors[t][0]+"m"+n+"\x1B["+wt.colors[t][1]+"m":n}s(ud,"stylizeWithColor");function ko(n){return typeof n=="function"}s(ko,"isFunction");function qa(n){return typeof n=="string"}s(qa,"isString");function ld(n){return typeof n=="number"}s(ld,"isNumber");function $a(n){return n===null}s($a,"isNull");function Ua(n,e){return Object.prototype.hasOwnProperty.call(n,e)}s(Ua,"hasOwn");function Lo(n){return Zo(n)&&qo(n)==="[object RegExp]"}s(Lo,"isRegExp");function Zo(n){return typeof n=="object"&&n!==null}s(Zo,"isObject");function No(n){return Zo(n)&&(qo(n)==="[object Error]"||n instanceof Error)}s(No,"isError");function Da(n){return Zo(n)&&qo(n)==="[object Date]"}s(Da,"isDate");function qo(n){return Object.prototype.toString.call(n)}s(qo,"objectToString");function dd(n){let e={};return n.forEach(function(t,r){e[t]=!0}),e}s(dd,"arrayToHash");function pd(n,e,t,r,o){let i=[];for(let a=0,c=e.length;a<c;++a)Ua(e,String(a))?i.push(Do(n,e,t,r,String(a),!0)):i.push("");return o.forEach(function(a){a.match(/^\d+$/)||i.push(Do(n,e,t,r,a,!0))}),i}s(pd,"formatArray");function Mo(n){return"["+Error.prototype.toString.call(n)+"]"}s(Mo,"formatError");function Pr(n,e,t){if(n.customInspect&&e&&ko(e.inspect)&&e.inspect!==wt&&!(e.constructor&&e.constructor.prototype===e)){let d=e.inspect(t,n);return qa(d)||(d=Pr(n,d,t)),d}let r=md(n,e);if(r)return r;let o=Object.keys(e),i=dd(o);try{n.showHidden&&Object.getOwnPropertyNames&&(o=Object.getOwnPropertyNames(e))}catch{}if(No(e)&&(o.indexOf("message")>=0||o.indexOf("description")>=0))return Mo(e);if(o.length===0){if(ko(e)){let d=e.name?": "+e.name:"";return n.stylize("[Function"+d+"]","special")}if(Lo(e))return n.stylize(RegExp.prototype.toString.call(e),"regexp");if(Da(e))return n.stylize(Date.prototype.toString.call(e),"date");if(No(e))return Mo(e)}let a="",c=!1,u=["{","}"];if(Array.isArray(e)&&(c=!0,u=["[","]"]),ko(e)&&(a=" [Function"+(e.name?": "+e.name:"")+"]"),Lo(e)&&(a=" "+RegExp.prototype.toString.call(e)),Da(e)&&(a=" "+Date.prototype.toUTCString.call(e)),No(e)&&(a=" "+Mo(e)),o.length===0&&(!c||e.length==0))return u[0]+a+u[1];if(t<0)return Lo(e)?n.stylize(RegExp.prototype.toString.call(e),"regexp"):n.stylize("[Object]","special");n.seen.push(e);let l;return c?l=pd(n,e,t,i,o):l=o.map(function(d){return Do(n,e,t,i,d,c)}),n.seen.pop(),fd(l,a,u)}s(Pr,"formatValue");function Do(n,e,t,r,o,i){let a,c,u;u={value:void 0};try{u.value=e[o]}catch{}try{Object.getOwnPropertyDescriptor&&(u=Object.getOwnPropertyDescriptor(e,o)||u)}catch{}if(u.get?u.set?c=n.stylize("[Getter/Setter]","special"):c=n.stylize("[Getter]","special"):u.set&&(c=n.stylize("[Setter]","special")),Ua(r,o)||(a="["+o+"]"),c||(n.seen.indexOf(u.value)<0?($a(t)?c=Pr(n,u.value,null):c=Pr(n,u.value,t-1),c.indexOf(`
|
|
27
27
|
`)>-1&&(i?c=c.split(`
|
|
28
28
|
`).map(function(l){return" "+l}).join(`
|
|
@@ -32,7 +32,7 @@ import{a as y,b as bt,e as Se,f as Kl,g as Ao,h as _o,i as Ql,j as Yl}from"./chu
|
|
|
32
32
|
`))):c=n.stylize("[Circular]","special")),Za(a)){if(i&&o.match(/^\d+$/))return c;a=JSON.stringify(""+o),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=n.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=n.stylize(a,"string"))}return a+": "+c}s(Do,"formatProperty");function md(n,e){if(Za(e))return n.stylize("undefined","undefined");if(qa(e)){let t="'"+JSON.stringify(e).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return n.stylize(t,"string")}if(ld(e))return n.stylize(""+e,"number");if(cd(e))return n.stylize(""+e,"boolean");if($a(e))return n.stylize("null","null")}s(md,"formatPrimitive");function fd(n,e,t){let r=0;return n.reduce(function(i,a){return r++,a.indexOf(`
|
|
33
33
|
`)>=0&&r++,i+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?t[0]+(e===""?"":e+`
|
|
34
34
|
`)+" "+n.join(`,
|
|
35
|
-
`)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}s(fd,"reduceToSingleString");var Ha=s((n,...e)=>Ma(wt,n,e),"format");var $o=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=Na(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=Ha(t,...e);let i=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}},Uo=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function gd(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}s(gd,"extract");var Ir;function Ce(n){let e=globalThis.DEBUG;Ir||(Ir=new Uo(gd(e)));let t=new $o(Ir,n);return Ir.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}s(Ce,"debug");var ae=class extends Error{static{s(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},k=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},f=class extends k{static{s(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}};var Nt=Ce("zuplo:runtime:external-service");function hd(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=y.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}s(hd,"getServiceAuth");async function Fa(n,e){let t=hd();if(t)if(Nt(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),i.headers=a;let c;if(t.customServiceMapping&&t.customServiceMapping[o])c=`https://${t.customServiceMapping[o]}`;else if(y.instance.useLegacyServiceRouting)c=`https://${o}.zuptunnel.com`;else{Nt("Using sha256 service routing");let d=y.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE){let p=await yd(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE),m=ja(d.ENVIRONMENT_TYPE),h=await Ho(`${d.ACCOUNT_NAME}-${d.PROJECT_NAME}-${m}`);h==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||h==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?c=`https://${p}.zuptunnel.com`:c=`https://${p}.t.zuplo.app`}else throw Nt("Cannot use sha256 service routing, missing build variables"),new k("Failed to generate fully qualified tunnel url.")}let u=new URL(`${c}${r.pathname}${r.search}`);Nt(`Calling external service: ${u.toString()}`);let l=await Er(u.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:c}),new k("Could not connect to secure tunnel.");return l}else throw Nt("Cannot call external service with Request object"),new k("Currently, we only support fetch(<some_string>, ...).");else throw Nt("There is no external service auth configured for this zup."),new k("There are no external services configured for this zup.")}s(Fa,"externalServiceHandler");async function yd(n,e,t,r){let o=n.toLowerCase(),i=e.toLowerCase(),a=t.toLowerCase(),c=ja(r);Nt(`Hashing service name: ${i}-${o}.${i}-${a}-${c}`);let u=await Ho(`${i}-${o}`),l=await Ho(`${i}-${a}-${c}`);return`${u}.${l}`}s(yd,"hashServiceName");async function Ho(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Ho,"hashSegment");function ja(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(ja,"sanitizeEnvironmentType");var za=new Map;za.set("service:",Fa);var Er=globalThis.fetch;function Fo(n,e){let t=bd(e);if(typeof n=="string"){let r=new URL(n),o=za.get(r.protocol);return o?o(n,t):Er(n,t)}else return Er(n,t)}s(Fo,"internalFetch");globalThis.fetch=Fo;var bd=s(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var wd={fetch:Fo},j=wd;Function.prototype.toString=function(){return"[native code]"};var Tr=globalThis,Ba=Tr.caches;if(Ba){let n=Ba.open;Tr.caches.open=function(e){let t=y.instance.deploymentName??y.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Tr.caches.default,Object.freeze(Tr.caches)}var Sr=new Set,Ga=new Set;function g(n){Ga.has(n)||(Ga.add(n),Sr.add(n))}s(g,"trackFeature");function Va(){let n=[...Sr];return Sr.clear(),n}s(Va,"getUnsentFeatures");function Wa(n){for(let e of n)Sr.add(e)}s(Wa,"restoreFeatures");function Xe(n,e){n.has("Authorization")||n.set("Authorization",`Bearer ${y.instance.authApiJWT}`),n.set("zp-rid",e??`global-${crypto.randomUUID()}`),n.set("zp-dn",y.instance.deploymentName??"unknown"),n.set("User-Agent",y.instance.systemUserAgent),n.set("zp-compat-date",y.instance.build.COMPATIBILITY_DATE??"none")}s(Xe,"setZuploHeaders");async function Rd(n,e={}){g("utility.zuplo-api-services");let{method:t="GET",data:r}=e,o=new URL(n,y.instance.zuploEdgeApiUrl),i=new Headers(e.headers);Xe(i),i.set("Content-Type","application/json");let a={method:t,headers:i};r&&(a.body=JSON.stringify(r));let c=await j.fetch(o,a),u;try{if(!c.ok)throw u=await c.clone().json(),new Error(`Error ${c.status}: ${JSON.stringify(u)||"Request failed"}`);if(c.status===204)return;u=await c.clone().json()}catch(l){throw new Error(l.message)}return u}s(Rd,"apiServices");var Ja=new Map,jo=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},et=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Ja.get(e);r||(r=new jo(t),Ja.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var zo="__zuplo-expiry-header",$n=class{static{s(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(zo);if(!i){try{await t.delete(r)}catch(u){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",u),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(u){this.logDebug("Handled failure to delete with CF cache because of expiration",u),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(zo,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),c=new Response(JSON.stringify(t),{headers:o});await i.put(a,c)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(zo,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var me=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new et(r),this.#n=new $n(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}async delete(e){this.#t.delete(e),await this.#n.delete(e)}};var Bo="__zuplo-expiry-header",Go=class{static{s(this,"StreamingZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://streaming-zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(Bo);if(!i){await t.delete(r).catch(c=>{this.logDebug(`StreamingZoneCache: error deleting missing expiry entry ${e}`,c)});return}let a=parseInt(i,10);if(Date.now()>=a){await t.delete(r).catch(c=>{this.logDebug(`StreamingZoneCache: error deleting expired entry ${e}`,c)});return}return o.body??void 0}catch(t){this.logDebug(`get(${e}) failed`,t);return}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`});o.set(Bo,`${Date.now()+r*1e3}`);let i=new Response(t,{headers:o}),a=await this.#r(),c=this.#o(e);await a.put(c,i)}async delete(e){try{await(await this.#r()).delete(this.#o(e))}catch(t){this.logDebug(`delete(${e}) fallback needed`,t),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate",[Bo]:`${Date.now()}`}),r=new Response("",{headers:t}),o=await this.#r(),i=this.#o(e);await o.put(i,r)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`StreamingZoneCache(${this.#t}):`,...e):"log"in this.#e&&this.#e.log.debug(`StreamingZoneCache(${this.#t}):`,...e)}};var Ka="zuplo-request-id",an="zp-rid",Vo="zp-body-removed",Mt="cf-ray",Qa="x-real-ip",Wo="cf-ipcity",Jo="cf-ipcontinent",Ko="cf-ipcountry",Qo="cf-iplongitude",Yo="cf-iplatitude",Ya="cf-region",Xa="cf-region-code",ec="cf-metro-code",tc="cf-postal-code",nc="cf-timezone",Cr="zp-ipcity",Or="zp-ipcontinent",Ar="zp-ipcountry",_r="zp-iplongitude",kr="zp-iplatitude",rc="true-client-ip",oc="x-forwarded-for",Un="zp-asn",Xo="zp-asorg",ei="zp-colo",Hn="zp-postalcode",Fn="zp-metrocode",ti="zp-region",jn="zp-regioncode",zn="zp-timezone",ic="zp-http-protocol",ni="x-akamai-edgescape",sc=[Wo,Jo,Ko,Qo,Yo,Un,Xo,ei,Hn,Fn,ti,jn,zn,ni],ac=["zp-","cf-"],cc=[an,Mt,Vo];var Bn=Symbol("zuplo_meters"),Gn=Symbol("zuplo_dynamic_meters"),Lr="system-logger";var fe=class n{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{trace as dp}from"@opentelemetry/api";import{SpanStatusCode as vd,trace as xd}from"@opentelemetry/api";import{SpanStatusCode as Zr,trace as qr}from"@opentelemetry/api";var uc=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function lc(n){uc=n}s(lc,"setTelemetryInitFunction");var dc=s(n=>uc(n),"proxyHandler");var Rt=class{static{s(this,"RuntimePlugin")}},Ee=class extends Rt{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Nr=class extends Ee{static{s(this,"MeteringPlugin")}},Vn=class extends Rt{static{s(this,"TelemetryPlugin")}};var Wn=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=s(async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new k("Error in custom 'problemResponseFormat'",{cause:i})}})}},Dt=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Wn.problemResponseFormat(e,t,r)}};function Mr(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Mr(t)}return Object.freeze(n)}s(Mr,"deepFreeze");var ue=class n extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return Mr(this.#e)}get params(){return Mr(this.#t)}user};var ai={},at=[],ri=[],oi=[],ii=[],si=[];var Dr={addPlugin(n){at.push(n)},addRequestHook(n){ri.push(n)},addResponseSendingHook(n){oi.push(n)},addResponseSendingFinalHook(n){ii.push(n)},addPreRoutingHook(n){si.push(n)}},mc=s(async(n,e)=>{if(ri.length===0)return n;let t=qr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of ri){let a=await t.startActiveSpan(i.name,async c=>{let u=await i(o,e);if(u instanceof ue||u instanceof Response)return c.end(),u;{let l=new f(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw c.end(),c.recordException(l),c.setStatus({code:Zr.ERROR}),l}});if(a instanceof ue)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),fc=s(async(n,e,t)=>{if(oi.length===0)return n;let r=qr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of oi)await r.startActiveSpan(a.name,async c=>{let u=await a(n,e,t);if(u instanceof Response)i=u,c.end();else{let l=new f(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw c.recordException(l),c.setStatus({code:Zr.ERROR}),c.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),gc=s(async(n,e,t)=>{if(ii.length===0)return;let r=qr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of ii)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(c){throw a.recordException(c),a.setStatus({code:Zr.ERROR}),a.end(),c}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),hc=s(async n=>{if(si.length===0)return n;let e=qr.getTracer("extension");return e.startActiveSpan("hook:preRouting",async t=>{try{let r=n;for(let o of si)r=await e.startActiveSpan(o.name,async a=>{try{let c=await o(r);if(c instanceof Request)return c;{let u=new k(`Invalid state - the PreRouting hook must return a Request. Received ${typeof c}.`);throw a.recordException(u),a.setStatus({code:Zr.ERROR}),u}}finally{a.end()}});return r}finally{t.end()}})},"invokePreRoutingHooks"),pc=!1;async function yc(n){if(!pc){n&&(g("runtime.extensions"),await n(Dr)),ai.value=Dr;for(let e of at)if(e instanceof Vn){let{requestHandlerProxy:t}=e.instrument({accountName:y.instance.build.ACCOUNT_NAME,projectName:y.instance.build.PROJECT_NAME,buildId:y.instance.build.BUILD_ID,zuploVersion:y.instance.build.ZUPLO_VERSION,compatibilityDate:y.instance.build.COMPATIBILITY_DATE,instanceId:y.instance.instanceId,environmentType:y.instance.loggingEnvironmentType,environmentStage:y.instance.loggingEnvironmentStage,deploymentName:y.instance.deploymentName});lc(t)}await Promise.all(at.map(async e=>{e instanceof Ee&&await e.initialize(Dr)})),Wn.setProblemResponseFormat(Dr.problemResponseFormat),pc=!0}}s(yc,"initializeRuntime");var ci={Json:"application/json",Form:"application/x-www-form-urlencoded"};function ui(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(ci.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(ci.Json)||!e?JSON.stringify(n):n}s(ui,"serialize");function cn(n){return Ie.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(Ie.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(cn,"isSystemRoute");var Te=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=s((e,t)=>async(r,o)=>xd.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(c){let u=t.errorHandler(r,o,"Error executing request handler.",c);return a.setStatus({code:vd.ERROR}),u}finally{a.end()}}),"#errorWrappedHandler");#t=s(({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=_e.getContextExtensions(i),c=[...e],u=s(async b=>{let P=c.pop();if(!P){let A=await this.#e(async B=>{let $=await r(B,i);return Pd($)},t)(b,i);try{await a.onHandlerResponse(A,b,i)}catch(B){return t.errorHandler(o,i,"Error invoking 'context.onHandlerResponse' hook",B)}return A}return P(o,i,t,u)},"nextPipe"),d=await u(o),p=new URL(o.url);if(cn(p)&&y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return d;let m=new Jn(o,d);i.dispatchEvent(m);let h=a.latestRequest,x;try{x=await m.mutableResponse}catch(b){return t.errorHandler(o,i,"Error retrieving mutableResponse",b)}try{x=await a.onResponseSending(x,h,i)}catch(b){return t.errorHandler(o,i,"Error invoking 'context.onResponseSending' hook",b)}try{x=await fc(x,h,i)}catch(b){return t.errorHandler(o,i,"Error invoking 'context.onResponseSending' hook",b)}i.dispatchEvent(new Kn(o,x));try{await a.onResponseSendingFinal(d,h,i)}catch(b){throw i.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}try{await gc(d,h,i)}catch(b){throw i.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}return x},"#toZuploPipeline")};function Pd(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(ui(n),{headers:{"content-type":"application/json"}})}s(Pd,"resultToResponse");var tt=class extends Rt{static{s(this,"MetricsPlugin")}};var ne=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new ae(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var ie=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=s(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=s(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var $r=class{static{s(this,"ZuploMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new ie("zuplo-metrics-transport",10,this.dispatchFunction,ne.getLogger(e))}pushMetrics(e,t){this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let{remoteLogURL:t,deploymentName:r}=y.instance,{ACCOUNT_NAME:o,PROJECT_NAME:i}=y.instance.build,a=e.map(p=>{let m=Object.assign({},p);return delete m.requestContentLength,delete m.responseContentLength,m}),c=Va(),u={metadata:{timestamp:new Date,accountName:o,projectName:i,deploymentName:r},metrics:a,features:c},l=new Headers({"content-type":"application/json"});Xe(l);let d=await j.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(u),headers:l});if(!d.ok){let p=await d.text();ne.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),Wa(c)}}catch(t){ne.getLogger(this.#e).error("Failed to send Zuplo metrics.",t)}},"dispatchFunction")};var xe=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;policies;systemRouteName;metadata;raw(){return{}}};function bc(n){let e=n.headers,t=e.get(rc);if(t)return t;let r=e.get(oc);if(r)return r.split(",")[0].trim()}s(bc,"getClientIp");var ke=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),c=n.headers.get(Mt)??void 0,u=bc(n),l=e.incomingRequestProperties,d;e.route instanceof xe&&(d=e.route.systemRouteName);let p=_e.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,contextId:e.contextId,parentContextId:e.parentContext?.contextId,requestId:e.requestId,parentRequestId:e.parentContext?.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:c,instanceId:y.instance.instanceId,userSub:p.user?.sub,clientIp:u},h=[];return!y.instance.isLocalDevelopment&&y.instance.remoteLogURL&&y.instance.remoteLogToken&&y.instance.loggingId&&h.push(new $r(e)),at.forEach(x=>{if(x instanceof tt){let b=x.getTransport();h.push(b)}}),h.forEach(x=>{x.pushMetrics(m,e)}),a},"metricsProcessor");var li=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url),u=y.instance.build,l={buildId:u.BUILD_ID,zuploVersion:u.ZUPLO_VERSION,compatibilityDate:u.COMPATIBILITY_DATE,apiVersion:u.API_VERSION,gitSha:u.GIT_SHA,timestamp:u.TIMESTAMP,isProduction:u.ENVIRONMENT_TYPE==="PRODUCTION"};if(c.searchParams.get("system_log")==="true"&&ne.getLogger(a).error("Test System Log",l),c.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(l,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new Te({processors:[ke],handler:t,gateway:e}),o=new xe({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var Ur=(R=>(R[R.CONTINUE=100]="CONTINUE",R[R.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",R[R.PROCESSING=102]="PROCESSING",R[R.EARLY_HINTS=103]="EARLY_HINTS",R[R.OK=200]="OK",R[R.CREATED=201]="CREATED",R[R.ACCEPTED=202]="ACCEPTED",R[R.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",R[R.NO_CONTENT=204]="NO_CONTENT",R[R.RESET_CONTENT=205]="RESET_CONTENT",R[R.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",R[R.MULTI_STATUS=207]="MULTI_STATUS",R[R.ALREADY_REPORTED=208]="ALREADY_REPORTED",R[R.IM_USED=226]="IM_USED",R[R.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",R[R.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",R[R.FOUND=302]="FOUND",R[R.SEE_OTHER=303]="SEE_OTHER",R[R.NOT_MODIFIED=304]="NOT_MODIFIED",R[R.USE_PROXY=305]="USE_PROXY",R[R.SWITCH_PROXY=306]="SWITCH_PROXY",R[R.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",R[R.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",R[R.BAD_REQUEST=400]="BAD_REQUEST",R[R.UNAUTHORIZED=401]="UNAUTHORIZED",R[R.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",R[R.FORBIDDEN=403]="FORBIDDEN",R[R.NOT_FOUND=404]="NOT_FOUND",R[R.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",R[R.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",R[R.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",R[R.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",R[R.CONFLICT=409]="CONFLICT",R[R.GONE=410]="GONE",R[R.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",R[R.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",R[R.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",R[R.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",R[R.URI_TOO_LONG=414]="URI_TOO_LONG",R[R.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",R[R.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",R[R.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",R[R.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",R[R.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",R[R.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",R[R.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",R[R.LOCKED=423]="LOCKED",R[R.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",R[R.TOO_EARLY=425]="TOO_EARLY",R[R.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",R[R.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",R[R.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",R[R.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",R[R.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",R[R.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",R[R.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",R[R.BAD_GATEWAY=502]="BAD_GATEWAY",R[R.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",R[R.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",R[R.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",R[R.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",R[R.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",R[R.LOOP_DETECTED=508]="LOOP_DETECTED",R[R.NOT_EXTENDED=510]="NOT_EXTENDED",R[R.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",R))(Ur||{}),wc={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var Id={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},di=Id;function Ed(n){return`${new URL(n.url).pathname}`}s(Ed,"instance");function Td(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=n.headers.get(Mt);return r&&(t.rayId=r),t}s(Td,"trace");var Sd=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Ed(e),trace:Td(e,t),...r},additionalHeaders:o,statusText:di[n.status]}),"merge"),pi=class{static{s(this,"HttpProblemsBase")}static format=s((e,t,r)=>"problem"in e?Dt.format(e,t,r):Dt.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:wc[e],...t}}},T=class extends pi{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=Sd(this.getProblemFromStatus(e),t,r,o,i);return Dt.format(a,t,r)}static continue=s((e,t,r,o)=>this.#e(200,e,t,r,o),"continue");static switchingProtocols=s((e,t,r,o)=>this.#e(101,e,t,r,o),"switchingProtocols");static processing=s((e,t,r,o)=>this.#e(102,e,t,r,o),"processing");static earlyHints=s((e,t,r,o)=>this.#e(103,e,t,r,o),"earlyHints");static ok=s((e,t,r,o)=>this.#e(200,e,t,r,o),"ok");static created=s((e,t,r,o)=>this.#e(201,e,t,r,o),"created");static accepted=s((e,t,r,o)=>this.#e(202,e,t,r,o),"accepted");static nonAuthoritativeInformation=s((e,t,r,o)=>this.#e(203,e,t,r,o),"nonAuthoritativeInformation");static noContent=s((e,t,r,o)=>this.#e(204,e,t,r,o),"noContent");static resetContent=s((e,t,r,o)=>this.#e(205,e,t,r,o),"resetContent");static partialContent=s((e,t,r,o)=>this.#e(206,e,t,r,o),"partialContent");static multiStatus=s((e,t,r,o)=>this.#e(207,e,t,r,o),"multiStatus");static alreadyReported=s((e,t,r,o)=>this.#e(208,e,t,r,o),"alreadyReported");static imUsed=s((e,t,r,o)=>this.#e(226,e,t,r,o),"imUsed");static multipleChoices=s((e,t,r,o)=>this.#e(300,e,t,r,o),"multipleChoices");static movedPermanently=s((e,t,r,o)=>this.#e(301,e,t,r,o),"movedPermanently");static found=s((e,t,r,o)=>this.#e(302,e,t,r,o),"found");static seeOther=s((e,t,r,o)=>this.#e(303,e,t,r,o),"seeOther");static notModified=s((e,t,r,o)=>this.#e(304,e,t,r,o),"notModified");static useProxy=s((e,t,r,o)=>this.#e(305,e,t,r,o),"useProxy");static switchProxy=s((e,t,r,o)=>this.#e(306,e,t,r,o),"switchProxy");static temporaryRedirect=s((e,t,r,o)=>this.#e(307,e,t,r,o),"temporaryRedirect");static permanentRedirect=s((e,t,r,o)=>this.#e(308,e,t,r,o),"permanentRedirect");static badRequest=s((e,t,r,o)=>this.#e(400,e,t,r,o),"badRequest");static unauthorized=s((e,t,r,o)=>this.#e(401,e,t,r,o),"unauthorized");static paymentRequired=s((e,t,r,o)=>this.#e(402,e,t,r,o),"paymentRequired");static forbidden=s((e,t,r,o)=>this.#e(403,e,t,r,o),"forbidden");static notFound=s((e,t,r,o)=>this.#e(404,e,t,r,o),"notFound");static methodNotAllowed=s((e,t,r,o)=>this.#e(405,e,t,r,o),"methodNotAllowed");static notAcceptable=s((e,t,r,o)=>this.#e(406,e,t,r,o),"notAcceptable");static proxyAuthenticationRequired=s((e,t,r,o)=>this.#e(407,e,t,r,o),"proxyAuthenticationRequired");static requestTimeout=s((e,t,r,o)=>this.#e(408,e,t,r,o),"requestTimeout");static conflict=s((e,t,r,o)=>this.#e(409,e,t,r,o),"conflict");static gone=s((e,t,r,o)=>this.#e(410,e,t,r,o),"gone");static lengthRequired=s((e,t,r,o)=>this.#e(411,e,t,r,o),"lengthRequired");static preconditionFailed=s((e,t,r,o)=>this.#e(412,e,t,r,o),"preconditionFailed");static contentTooLarge=s((e,t,r,o)=>this.#e(413,e,t,r,o),"contentTooLarge");static uriTooLong=s((e,t,r,o)=>this.#e(414,e,t,r,o),"uriTooLong");static unsupportedMediaType=s((e,t,r,o)=>this.#e(415,e,t,r,o),"unsupportedMediaType");static rangeNotSatisfiable=s((e,t,r,o)=>this.#e(416,e,t,r,o),"rangeNotSatisfiable");static expectationFailed=s((e,t,r,o)=>this.#e(417,e,t,r,o),"expectationFailed");static imATeapot=s((e,t,r,o)=>this.#e(418,e,t,r,o),"imATeapot");static misdirectedRequest=s((e,t,r,o)=>this.#e(421,e,t,r,o),"misdirectedRequest");static unprocessableContent=s((e,t,r,o)=>this.#e(422,e,t,r,o),"unprocessableContent");static locked=s((e,t,r,o)=>this.#e(423,e,t,r,o),"locked");static failedDependency=s((e,t,r,o)=>this.#e(424,e,t,r,o),"failedDependency");static tooEarly=s((e,t,r,o)=>this.#e(425,e,t,r,o),"tooEarly");static upgradeRequired=s((e,t,r,o)=>this.#e(426,e,t,r,o),"upgradeRequired");static preconditionRequired=s((e,t,r,o)=>this.#e(428,e,t,r,o),"preconditionRequired");static tooManyRequests=s((e,t,r,o)=>this.#e(429,e,t,r,o),"tooManyRequests");static requestHeaderFieldsTooLarge=s((e,t,r,o)=>this.#e(431,e,t,r,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=s((e,t,r,o)=>this.#e(451,e,t,r,o),"unavailableForLegalReasons");static internalServerError=s((e,t,r,o)=>this.#e(500,e,t,r,o),"internalServerError");static notImplemented=s((e,t,r,o)=>this.#e(501,e,t,r,o),"notImplemented");static badGateway=s((e,t,r,o)=>this.#e(502,e,t,r,o),"badGateway");static serviceUnavailable=s((e,t,r,o)=>this.#e(503,e,t,r,o),"serviceUnavailable");static gatewayTimeout=s((e,t,r,o)=>this.#e(504,e,t,r,o),"gatewayTimeout");static httpVersionNotSupported=s((e,t,r,o)=>this.#e(505,e,t,r,o),"httpVersionNotSupported");static variantAlsoNegotiates=s((e,t,r,o)=>this.#e(506,e,t,r,o),"variantAlsoNegotiates");static insufficientStorage=s((e,t,r,o)=>this.#e(507,e,t,r,o),"insufficientStorage");static loopDetected=s((e,t,r,o)=>this.#e(508,e,t,r,o),"loopDetected");static notExtended=s((e,t,r,o)=>this.#e(510,e,t,r,o),"notExtended");static networkAuthenticationRequired=s((e,t,r,o)=>this.#e(511,e,t,r,o),"networkAuthenticationRequired")};var{toString:Cd}=Object.prototype,{propertyIsEnumerable:Od}=Object.prototype;function mi(n){return Cd.call(n)}s(mi,"toString");function qe(n){return typeof n=="string"}s(qe,"isString");function un(n){return qe(n)&&n!==""}s(un,"isNonEmptyString");function Rc(n){return mi(n)==="[object RegExp]"}s(Rc,"isRegexp");function vc(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Od.call(n,e))]}s(vc,"getOwnEnumerableKeys");function Zt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Zt,"isObject");function fi(n){return typeof n=="number"&&!isNaN(n)}s(fi,"isNumber");function gi(n){return n===!0||n===!1}s(gi,"isBoolean");function xc(n){return typeof n>"u"}s(xc,"isUndefined");function Pc(n){return xc(n)||n===null}s(Pc,"isUndefinedOrNull");function Qn(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Qn,"isErrorLike");var Ic=new Map;function vt(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new f("Malformed input string");let e=Ic.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),c=parseInt(i[1],10);for(let u=a;u<=c;u++)r.push(u)}else r.push(parseInt(o,10))}return Ic.set(n,r),r}s(vt,"statusCodesStringToNumberArray");function ct(n,e,t){if(!e.startsWith("."))throw new f(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(i=>{if(o===void 0)throw new k(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(ct,"getValueFromRequestUser");function ut(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new f("Received an array that contains non-string values.");return n}if(qe(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new f(`Expected type of string, received type '${typeof n}'`)}s(ut,"parseValueToStringArray");function Ec(n){if(n==null)return[];if(!Array.isArray(n))throw new f(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!Zt(t))throw new f(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!un(t.name))throw new f("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!fi(t.maxAge))throw new f(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!gi(t.allowCredentials))throw new f("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=hi(t,"allowedHeaders"),o=hi(t,"allowedMethods"),i=hi(t,"exposeHeaders"),a;try{a=ut(t.allowedOrigins)}catch(u){throw new f(`Value of 'allowedOrigins' on custom cors policies is invalid. ${u.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(Ec,"parseCorsPolicies");function hi(n,e){let t;if(n[e]!==void 0)try{t=ut(n[e])}catch(r){throw new f(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}s(hi,"parseOptionalProperty");var Hr=s((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Fr=s((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var yi=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,c)=>{let u=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,c,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(u,l);if(!m)return T.notFound(a,c);let h=m.routeConfiguration,x=Ad(l,d,p,h,t);return x.isValid?new Response(void 0,{status:200,statusText:"OK",headers:x.headers}):(x.error&&c.log.warn(x.error),T.notFound(a,c))},"optionsHandler"),o=new Te({processors:[ke],handler:r,gateway:e}),i=new xe({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),Ad=s((n,e,t,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new f(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let c=Hr(a.allowedOrigins,t);return c?{isValid:!0,headers:Fr(a,c)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Tc=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new Te({processors:[ke],handler:t,gateway:e}),o=new xe({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var xt=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.metadata=e.metadata,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;metadata;custom;methods;handler;corsPolicy;policies};var _d=new xe({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Sc=s((n,e)=>{let t=s(async(o,i)=>{let a=ai.value?.notFoundHandler;if(a){let c=new URL(o.url);return a(o,i,{get routesMatchedByPathOnly(){return n.lookupByPathOnly(c.pathname).map(l=>l.routeConfiguration).filter(l=>l instanceof xt)}})}return T.notFound(o,i)},"notFoundHandler"),r=new Te({processors:[ke],handler:t,gateway:e});n.addRoute(_d,r.execute)},"registerNotMatchedHandler");var kd=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Cc=s(n=>{kd.forEach(e=>n.delete(e))},"stripCorsHeaders"),jr=s(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Cc(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new ae(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Ld(o,t.routeData.corsPolicies),c=Nd(n,a),u=new Headers(i.headers);return Cc(u),Object.entries(c).forEach(([d,p])=>{u.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:u,webSocket:i.webSocket})},"corsProcessor"),Ld=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new f(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Nd=s((n,e)=>{let t=Hr(e.allowedOrigins,n.headers.get("origin"));return t?Fr(e,t):{}},"getCorsHeaders");var bi=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:y.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new Te({processors:[jr],handler:t,gateway:e}),o=new xe({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as Oc,trace as Ac}from"@opentelemetry/api";var lt={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var zr=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!qe(t))throw new k(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ye=class extends zr{static{s(this,"InboundPolicy")}},Pt=class extends zr{static{s(this,"OutboundPolicy")}};var vi=class extends ye{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},xi=class extends Pt{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},wi=new Map;function Yn(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!wi.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new f(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let c=a.handler?.module[a.handler.export];if(typeof c!="function")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof c}')`);let u;if(typeof c!="function")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof c}')`);if(c.prototype instanceof ye)u=new c(a.handler.options,a.name);else if(typeof c=="function")u=new vi(c,a.handler.options,a.name);else throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof c}')`);if(typeof u.handler!="function")throw new f(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof u.handler}')`);wi.set(a.name,u)}),t.map(i=>{let a=wi.get(i);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}s(Yn,"getInboundPolicyInstances");var Ri=new Map;function Xn(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],r=n.path),t.filter(i=>!Ri.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new f(`Invalid state - no Policy with the name '${i}' on route '${r}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let c=a.handler?.module[a.handler.export],u;if(typeof c!="function")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof c}')`);if(c.prototype instanceof Pt)u=new c(a.handler.options??{},a.name);else if(typeof c=="function")u=new xi(c,a.handler.options??{},a.name);else throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof c}')`);if(typeof u.handler!="function")throw new f(`Invalid state - invalid handler on policy '${i}' on route '${r}'`);Ri.set(a.name,u)}),t.map(i=>{let a=Ri.get(i);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}s(Xn,"getOutboundPolicyInstances");var Pi=s(n=>async(e,t)=>{let r=_e.getContextExtensions(t),o=Ac.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{try{let a=[...n],c=e;for(;a.length>0;){let u=a.shift();if(!u)return c;let l=await o.startActiveSpan(`policy:${u.policyName}`,async d=>{let p=await u.handler(c,t);if(p instanceof Request||p instanceof ue||p instanceof Response)return d.end(),p instanceof Response||p instanceof ue?p:new ue(p);{let m=new f(`Invalid state - invalid handler on policy '${u.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Oc.ERROR}),d.recordException(m),m}});if(l instanceof ue)c=l;else if(l instanceof Request)c=new ue(l);else if(l instanceof Response)return l;r.latestRequest=c}return c}finally{i.end()}})},"toStackedInboundHandler"),Ii=s(n=>async(e,t,r)=>{let o=Ac.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{try{let a=[...n],c=e;for(;a.length>0;){let u=a.shift();if(!u)return c;c=await o.startActiveSpan(`policy:${u.policyName}`,async d=>{try{d.setAttribute(lt.PolicyName,u.policyName),d.setAttribute(lt.PolicyType,u.policyType);let p=await u.handler(c,t,r);if(p instanceof Response)return p;{let m=new f(`Invalid state - invalid handler on policy '${u.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Oc.ERROR}),d.recordException(m),m}}finally{d.end()}})}return c}finally{i.end()}})},"toStackedOutboundHandler"),Br=s(async(n,e,t,r)=>{let o=Yn(e.route,t.routeData.policies),i=Xn(e.route,t.routeData.policies);return kc({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function _c({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>kc({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(_c,"createInternalPolicyProcessor");async function kc({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=Pi(t);try{let c=await a(n,e);if(c instanceof Response)return c;let u=await i(c),l=Ii(r),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(u,n,e):d=u.ok?l(u,n,e):u,d}catch(c){return o.errorHandler(n,e,"Error executing policies",c)}}s(kc,"executePolicyProcessor");var Dc=Jl(Mc(),1);function Zc(n,e){try{let t=/v\d+(-\d+)?/g,o=(0,Dc.parse)(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(Zc,"devPortalBaseURL");var qc="/__zuplo/dev-portal",Bd="dev-portal-id",Gd="dev-portal-host",Vd="zp-account",Wd="zp-project",Jd="dev-portal-build",Kd=`
|
|
35
|
+
`)+" "+t[1]:t[0]+e+" "+n.join(", ")+" "+t[1]}s(fd,"reduceToSingleString");var Ha=s((n,...e)=>Ma(wt,n,e),"format");var $o=class{static{s(this,"Debugger")}manager;ns;color;last;enabled;constructor(e,t){this.manager=e,this.ns=t,this.color=Na(t),this.last=0,this.enabled=e.enabled.some(r=>r.test(t))}log(...e){if(!this.enabled)return;let t,r=e[0];typeof r=="function"?t=r():t=String(r);let o=Date.now()-(this.last||Date.now());t=Ha(t,...e);let i=`${this.color(this.ns)} ${t} ${this.color(`+${o}ms`)}`;console.log(i),this.last=Date.now()}},Uo=class{static{s(this,"DebugManager")}debuggers;enabled;constructor(e){this.debuggers=new Map,this.enabled=e??[]}};function gd(n){return!n||n.length===0?[]:(n=n.replace(/\s/g,"").replace(/\*/g,".+"),n.split(",").map(e=>new RegExp(`^${e}$`)))}s(gd,"extract");var Ir;function Ce(n){let e=globalThis.DEBUG;Ir||(Ir=new Uo(gd(e)));let t=new $o(Ir,n);return Ir.debuggers.set(n,t),Object.assign(t.log.bind(t),{self:t})}s(Ce,"debug");var ae=class extends Error{static{s(this,"SystemError")}constructor(e,t){super(e,t),this.name="InternalError"}},k=class extends Error{static{s(this,"RuntimeError")}extensionMembers;constructor(e,t){typeof e=="string"?super(e,t):(super(e.message,t),this.extensionMembers=e.extensionMembers),this.name="RuntimeError"}},f=class extends k{static{s(this,"ConfigurationError")}constructor(e,t){super(e,t),this.name="ConfigurationError"}};var Nt=Ce("zuplo:runtime:external-service");function hd(){let n,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:e}=y.instance.runtime;if(e&&e!=="undefined")try{let t=atob(e);n=JSON.parse(t)}catch{}return n}s(hd,"getServiceAuth");async function Fa(n,e){let t=hd();if(t)if(Nt(`Using external service auth. ClientId: ${t.clientId})`),typeof n=="string"){let r=new URL(n),o=r.hostname,i=e??{},a=new Headers(i.headers||{});a.set("CF-Access-Client-Id",t.clientId),a.set("CF-Access-Client-Secret",t.clientSecret),i.headers=a;let c;if(t.customServiceMapping&&t.customServiceMapping[o])c=`https://${t.customServiceMapping[o]}`;else if(y.instance.useLegacyServiceRouting)c=`https://${o}.zuptunnel.com`;else{Nt("Using sha256 service routing");let d=y.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE){let p=await yd(o,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE),m=ja(d.ENVIRONMENT_TYPE),h=await Ho(`${d.ACCOUNT_NAME}-${d.PROJECT_NAME}-${m}`);h==="40d7ad502f5d743997999594c177184a00161a77865423511f3a1ea21eb5a5e"||h==="d05bffe8fa91a300187d2cf43e8aa4a56bd809c442ae10d1ee49af7d29a5a11"?c=`https://${p}.zuptunnel.com`:c=`https://${p}.t.zuplo.app`}else throw Nt("Cannot use sha256 service routing, missing build variables"),new k("Failed to generate fully qualified tunnel url.")}let u=new URL(`${c}${r.pathname}${r.search}`);Nt(`Calling external service: ${u.toString()}`);let l=await Er(u.toString(),i);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:t.clientId,tunnelHost:c}),new k("Could not connect to secure tunnel.");return l}else throw Nt("Cannot call external service with Request object"),new k("Currently, we only support fetch(<some_string>, ...).");else throw Nt("There is no external service auth configured for this zup."),new k("There are no external services configured for this zup.")}s(Fa,"externalServiceHandler");async function yd(n,e,t,r){let o=n.toLowerCase(),i=e.toLowerCase(),a=t.toLowerCase(),c=ja(r);Nt(`Hashing service name: ${i}-${o}.${i}-${a}-${c}`);let u=await Ho(`${i}-${o}`),l=await Ho(`${i}-${a}-${c}`);return`${u}.${l}`}s(yd,"hashServiceName");async function Ho(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("").slice(0,-1)}s(Ho,"hashSegment");function ja(n){let e=n.toLowerCase();switch(e){case"production":case"preview":return e;default:return"working-copy"}}s(ja,"sanitizeEnvironmentType");var za=new Map;za.set("service:",Fa);var Er=globalThis.fetch;function Fo(n,e){let t=bd(e);if(typeof n=="string"){let r=new URL(n),o=za.get(r.protocol);return o?o(n,t):Er(n,t)}else return Er(n,t)}s(Fo,"internalFetch");globalThis.fetch=Fo;var bd=s(n=>{if(!n||n instanceof Request)return n;let e=n;if(!e.zuplo)return n;let t=n;return t.cf={cacheEverything:e.zuplo?.cacheEverything,cacheTtl:e.zuplo?.cacheTtlSeconds},delete n.zuplo,n},"transformInit");var wd={fetch:Fo},j=wd;Function.prototype.toString=function(){return"[native code]"};var Tr=globalThis,Ba=Tr.caches;if(Ba){let n=Ba.open;Tr.caches.open=function(e){let t=y.instance.deploymentName??y.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Tr.caches.default,Object.freeze(Tr.caches)}var Sr=new Set,Ga=new Set;function g(n){Ga.has(n)||(Ga.add(n),Sr.add(n))}s(g,"trackFeature");function Va(){let n=[...Sr];return Sr.clear(),n}s(Va,"getUnsentFeatures");function Wa(n){for(let e of n)Sr.add(e)}s(Wa,"restoreFeatures");function Xe(n,e){n.has("Authorization")||n.set("Authorization",`Bearer ${y.instance.authApiJWT}`),n.set("zp-rid",e??`global-${crypto.randomUUID()}`),n.set("zp-dn",y.instance.deploymentName??"unknown"),n.set("User-Agent",y.instance.systemUserAgent),n.set("zp-compat-date",y.instance.build.COMPATIBILITY_DATE??"none")}s(Xe,"setZuploHeaders");async function Rd(n,e={}){g("utility.zuplo-api-services");let{method:t="GET",data:r}=e,o=new URL(n,y.instance.zuploEdgeApiUrl),i=new Headers(e.headers);Xe(i),i.set("Content-Type","application/json");let a={method:t,headers:i};r&&(a.body=JSON.stringify(r));let c=await j.fetch(o,a),u;try{if(!c.ok)throw u=await c.clone().json(),new Error(`Error ${c.status}: ${JSON.stringify(u)||"Request failed"}`);if(c.status===204)return;u=await c.clone().json()}catch(l){throw new Error(l.message)}return u}s(Rd,"apiServices");var Ja=new Map,jo=class{static{s(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#r=[];get(e){let t=this.#n.get(e);if(!t)return;let r=Date.now();if(r>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=r,this.#o(),t?.data}put(e,t,r){if(r<=0)return;if(this.#n.size>=this.#e){let a=this.#r.shift();a&&this.#n.delete(a)}let o=Date.now(),i={created:o,lastUsed:o,expiresAt:o+r*1e3,data:t};this.#r.push(e),this.#n.set(e,i)}delete(e){let t=this.#r.indexOf(e);t>=0&&this.#r.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#o(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,r)=>{t.expiresAt>=e&&this.#n.delete(r)})}},et=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Ja.get(e);r||(r=new jo(t),Ja.set(e,r)),this.#e=r}name;#e;get(e){return this.#e.get(e)}put(e,t,r){return this.#e.put(e,t,r)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var zo="__zuplo-expiry-header",$n=class{static{s(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(zo);if(!i){try{await t.delete(r)}catch(u){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",u),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(u){this.logDebug("Handled failure to delete with CF cache because of expiration",u),await this.deleteFallback(e)}return}return await o.json()}catch(t){this.logDebug(t)}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`,"content-type":"application/json"});o.set(zo,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),c=new Response(JSON.stringify(t),{headers:o});await i.put(a,c)}async delete(e){let t=await this.#r(),r=this.#o(e);try{await t.delete(r)}catch(o){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",o),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(zo,`${Date.now()}`);let r=await this.#r(),o=this.#o(e),i=new Response("",{headers:t});await r.put(o,i)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var me=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new et(r),this.#n=new $n(r,t),this.#r=t}#e;#t;#n;#r;async get(e){let t=this.#t.get(e);if(t)return t;let r=await this.#n.get(e);if(r){let o=Math.floor((r.expires-Date.now())/1e3);if(o>0)return this.#t.put(e,r.data,o),r.data}}put(e,t,r){this.#t.put(e,t,r);let o={data:t,expires:Date.now()+r*1e3},i=this.#n.put(e,o,r).catch(a=>{this.#r.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#r.waitUntil(i)}async delete(e){this.#t.delete(e),await this.#n.delete(e)}};var Bo="__zuplo-expiry-header",Go=class{static{s(this,"StreamingZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#r(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#o(e){return new Request(`https://streaming-zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#r(),r=this.#o(e),o=await t.match(r);if(!o)return;let i=o.headers.get(Bo);if(!i){await t.delete(r).catch(c=>{this.logDebug(`StreamingZoneCache: error deleting missing expiry entry ${e}`,c)});return}let a=parseInt(i,10);if(Date.now()>=a){await t.delete(r).catch(c=>{this.logDebug(`StreamingZoneCache: error deleting expired entry ${e}`,c)});return}return o.body??void 0}catch(t){this.logDebug(`get(${e}) failed`,t);return}}async put(e,t,r){let o=new Headers({"cache-control":`s-maxage=${r}, must-revalidate`});o.set(Bo,`${Date.now()+r*1e3}`);let i=new Response(t,{headers:o}),a=await this.#r(),c=this.#o(e);await a.put(c,i)}async delete(e){try{await(await this.#r()).delete(this.#o(e))}catch(t){this.logDebug(`delete(${e}) fallback needed`,t),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate",[Bo]:`${Date.now()}`}),r=new Response("",{headers:t}),o=await this.#r(),i=this.#o(e);await o.put(i,r)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`StreamingZoneCache(${this.#t}):`,...e):"log"in this.#e&&this.#e.log.debug(`StreamingZoneCache(${this.#t}):`,...e)}};var Ka="zuplo-request-id",an="zp-rid",Vo="zp-body-removed",Mt="cf-ray",Qa="x-real-ip",Wo="cf-ipcity",Jo="cf-ipcontinent",Ko="cf-ipcountry",Qo="cf-iplongitude",Yo="cf-iplatitude",Ya="cf-region",Xa="cf-region-code",ec="cf-metro-code",tc="cf-postal-code",nc="cf-timezone",Cr="zp-ipcity",Or="zp-ipcontinent",Ar="zp-ipcountry",_r="zp-iplongitude",kr="zp-iplatitude",rc="true-client-ip",oc="x-forwarded-for",Un="zp-asn",Xo="zp-asorg",ei="zp-colo",Hn="zp-postalcode",Fn="zp-metrocode",ti="zp-region",jn="zp-regioncode",zn="zp-timezone",ic="zp-http-protocol",ni="x-akamai-edgescape",sc=[Wo,Jo,Ko,Qo,Yo,Un,Xo,ei,Hn,Fn,ti,jn,zn,ni],ac=["zp-","cf-"],cc=[an,Mt,Vo];var Bn=Symbol("zuplo_meters"),Gn=Symbol("zuplo_dynamic_meters"),Lr="system-logger";var fe=class n{static{s(this,"ContextData")}static#e;#t;constructor(e){this.#t=e}set(e,t){n.set(e,this.#t,t)}get(e){return n.get(e,this.#t)}static set(e,t,r){n.#e||(n.#e=new WeakMap);let o=n.#e.get(e);o||(o=new Map),o.set(t,r),n.#e.set(e,o)}static get(e,t){return n.#e||(n.#e=new WeakMap),n.#e.get(e)?.get(t)}};import{trace as dp}from"@opentelemetry/api";import{SpanStatusCode as vd,trace as xd}from"@opentelemetry/api";import{SpanStatusCode as Zr,trace as qr}from"@opentelemetry/api";var uc=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function lc(n){uc=n}s(lc,"setTelemetryInitFunction");var dc=s(n=>uc(n),"proxyHandler");var Rt=class{static{s(this,"RuntimePlugin")}},Ee=class extends Rt{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Nr=class extends Ee{static{s(this,"MeteringPlugin")}},Vn=class extends Rt{static{s(this,"TelemetryPlugin")}};var Wn=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=s(async e=>{let t=e.problem,r=JSON.stringify(t,null,2);return new Response(r,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new k("Error in custom 'problemResponseFormat'",{cause:i})}})}},Dt=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Wn.problemResponseFormat(e,t,r)}};function Mr(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Mr(t)}return Object.freeze(n)}s(Mr,"deepFreeze");var ue=class n extends Request{static{s(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let r=t?.params;r?this.#t=r:e instanceof n?this.#t=e.#t:this.#t={};let o=t?.user;o?this.user=o:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[r,o]of t.entries())e[r]=o;this.#e=e}return Mr(this.#e)}get params(){return Mr(this.#t)}user};var ai={},at=[],ri=[],oi=[],ii=[],si=[];var Dr={addPlugin(n){at.push(n)},addRequestHook(n){ri.push(n)},addResponseSendingHook(n){oi.push(n)},addResponseSendingFinalHook(n){ii.push(n)},addPreRoutingHook(n){si.push(n)}},mc=s(async(n,e)=>{if(ri.length===0)return n;let t=qr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of ri){let a=await t.startActiveSpan(i.name,async c=>{let u=await i(o,e);if(u instanceof ue||u instanceof Response)return c.end(),u;{let l=new f(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw c.end(),c.recordException(l),c.setStatus({code:Zr.ERROR}),l}});if(a instanceof ue)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),fc=s(async(n,e,t)=>{if(oi.length===0)return n;let r=qr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of oi)await r.startActiveSpan(a.name,async c=>{let u=await a(n,e,t);if(u instanceof Response)i=u,c.end();else{let l=new f(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw c.recordException(l),c.setStatus({code:Zr.ERROR}),c.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),gc=s(async(n,e,t)=>{if(ii.length===0)return;let r=qr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of ii)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(c){throw a.recordException(c),a.setStatus({code:Zr.ERROR}),a.end(),c}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),hc=s(async n=>{if(si.length===0)return n;let e=qr.getTracer("extension");return e.startActiveSpan("hook:preRouting",async t=>{try{let r=n;for(let o of si)r=await e.startActiveSpan(o.name,async a=>{try{let c=await o(r);if(c instanceof Request)return c;{let u=new k(`Invalid state - the PreRouting hook must return a Request. Received ${typeof c}.`);throw a.recordException(u),a.setStatus({code:Zr.ERROR}),u}}finally{a.end()}});return r}finally{t.end()}})},"invokePreRoutingHooks"),pc=!1;async function yc(n){if(!pc){n&&(g("runtime.extensions"),await n(Dr)),ai.value=Dr;for(let e of at)if(e instanceof Vn){let{requestHandlerProxy:t}=e.instrument({accountName:y.instance.build.ACCOUNT_NAME,projectName:y.instance.build.PROJECT_NAME,buildId:y.instance.build.BUILD_ID,zuploVersion:y.instance.build.ZUPLO_VERSION,compatibilityDate:y.instance.build.COMPATIBILITY_DATE,instanceId:y.instance.instanceId,environmentType:y.instance.loggingEnvironmentType,environmentStage:y.instance.loggingEnvironmentStage,deploymentName:y.instance.deploymentName});lc(t)}await Promise.all(at.map(async e=>{e instanceof Ee&&await e.initialize(Dr)})),Wn.setProblemResponseFormat(Dr.problemResponseFormat),pc=!0}}s(yc,"initializeRuntime");var ci={Json:"application/json",Form:"application/x-www-form-urlencoded"};function ui(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(ci.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(ci.Json)||!e?JSON.stringify(n):n}s(ui,"serialize");function cn(n){return Ie.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(Ie.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(cn,"isSystemRoute");var Te=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=s((e,t)=>async(r,o)=>xd.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(c){let u=t.errorHandler(r,o,"Error executing request handler.",c);return a.setStatus({code:vd.ERROR}),u}finally{a.end()}}),"#errorWrappedHandler");#t=s(({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=_e.getContextExtensions(i),c=[...e],u=s(async b=>{let P=c.pop();if(!P){let A=await this.#e(async B=>{let $=await r(B,i);return Pd($)},t)(b,i);try{await a.onHandlerResponse(A,b,i)}catch(B){return t.errorHandler(o,i,"Error invoking 'context.onHandlerResponse' hook",B)}return A}return P(o,i,t,u)},"nextPipe"),d=await u(o),p=new URL(o.url);if(cn(p)&&y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return d;let m=new Jn(o,d);i.dispatchEvent(m);let h=a.latestRequest,w;try{w=await m.mutableResponse}catch(b){return t.errorHandler(o,i,"Error retrieving mutableResponse",b)}try{w=await a.onResponseSending(w,h,i)}catch(b){return t.errorHandler(o,i,"Error invoking 'context.onResponseSending' hook",b)}try{w=await fc(w,h,i)}catch(b){return t.errorHandler(o,i,"Error invoking 'context.onResponseSending' hook",b)}i.dispatchEvent(new Kn(o,w));try{await a.onResponseSendingFinal(d,h,i)}catch(b){throw i.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}try{await gc(d,h,i)}catch(b){throw i.log.error("Error invoking 'runtime.onResponseSending' hook",b),b}return w},"#toZuploPipeline")};function Pd(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(ui(n),{headers:{"content-type":"application/json"}})}s(Pd,"resultToResponse");var tt=class extends Rt{static{s(this,"MetricsPlugin")}};var ne=class n{static{s(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let r=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(r),new ae(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var ie=class{static{s(this,"BatchDispatch")}constructor(e,t,r,o){this.#t=e,this.#i=t,this.#r=r,this.#n=o??console}#e=void 0;#t;#n;#r;#o=[];#i;enqueue=s(e=>{this.#o.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#o.length>0){let r=[...this.#o];this.#o.length=0,this.#e=void 0,this.#r(r).catch(o=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,o.message,o.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=s(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var $r=class{static{s(this,"ZuploMetricsTransport")}#e;#t;constructor(e){this.#e=e,this.#t=new ie("zuplo-metrics-transport",10,this.dispatchFunction,ne.getLogger(e))}pushMetrics(e,t){this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let{remoteLogURL:t,deploymentName:r}=y.instance,{ACCOUNT_NAME:o,PROJECT_NAME:i}=y.instance.build,a=e.map(p=>{let m=Object.assign({},p);return delete m.requestContentLength,delete m.responseContentLength,m}),c=Va(),u={metadata:{timestamp:new Date,accountName:o,projectName:i,deploymentName:r},metrics:a,features:c},l=new Headers({"content-type":"application/json"});Xe(l);let d=await j.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(u),headers:l});if(!d.ok){let p=await d.text();ne.getLogger(this.#e).error(`Metrics POST responded ${d.status}: ${d.statusText}`,p),Wa(c)}}catch(t){ne.getLogger(this.#e).error("Failed to send Zuplo metrics.",t)}},"dispatchFunction")};var xe=class{static{s(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:r,systemRouteName:o,corsPolicy:i="none"}){this.label=e,this.path=t,this.methods=r,this.corsPolicy=i,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;policies;systemRouteName;metadata;raw(){return{}}};function bc(n){let e=n.headers,t=e.get(rc);if(t)return t;let r=e.get(oc);if(r)return r.split(",")[0].trim()}s(bc,"getClientIp");var ke=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),c=n.headers.get(Mt)??void 0,u=bc(n),l=e.incomingRequestProperties,d;e.route instanceof xe&&(d=e.route.systemRouteName);let p=_e.getContextExtensions(e).latestRequest,m={timestamp:o,statusCode:a.status,durationMs:Date.now()-i,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,contextId:e.contextId,parentContextId:e.parentContext?.contextId,requestId:e.requestId,parentRequestId:e.parentContext?.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:c,instanceId:y.instance.instanceId,userSub:p.user?.sub,clientIp:u},h=[];return!y.instance.isLocalDevelopment&&y.instance.remoteLogURL&&y.instance.remoteLogToken&&y.instance.loggingId&&h.push(new $r(e)),at.forEach(w=>{if(w instanceof tt){let b=w.getTransport();h.push(b)}}),h.forEach(w=>{w.pushMetrics(m,e)}),a},"metricsProcessor");var li=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url),u=y.instance.build,l={buildId:u.BUILD_ID,zuploVersion:u.ZUPLO_VERSION,compatibilityDate:u.COMPATIBILITY_DATE,apiVersion:u.API_VERSION,gitSha:u.GIT_SHA,timestamp:u.TIMESTAMP,isProduction:u.ENVIRONMENT_TYPE==="PRODUCTION"};if(c.searchParams.get("system_log")==="true"&&ne.getLogger(a).error("Test System Log",l),c.searchParams.get("error")==="true")throw new Error("this is an unhandled error");return new Response(JSON.stringify(l,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new Te({processors:[ke],handler:t,gateway:e}),o=new xe({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var Ur=(v=>(v[v.CONTINUE=100]="CONTINUE",v[v.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",v[v.PROCESSING=102]="PROCESSING",v[v.EARLY_HINTS=103]="EARLY_HINTS",v[v.OK=200]="OK",v[v.CREATED=201]="CREATED",v[v.ACCEPTED=202]="ACCEPTED",v[v.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",v[v.NO_CONTENT=204]="NO_CONTENT",v[v.RESET_CONTENT=205]="RESET_CONTENT",v[v.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",v[v.MULTI_STATUS=207]="MULTI_STATUS",v[v.ALREADY_REPORTED=208]="ALREADY_REPORTED",v[v.IM_USED=226]="IM_USED",v[v.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",v[v.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",v[v.FOUND=302]="FOUND",v[v.SEE_OTHER=303]="SEE_OTHER",v[v.NOT_MODIFIED=304]="NOT_MODIFIED",v[v.USE_PROXY=305]="USE_PROXY",v[v.SWITCH_PROXY=306]="SWITCH_PROXY",v[v.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",v[v.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",v[v.BAD_REQUEST=400]="BAD_REQUEST",v[v.UNAUTHORIZED=401]="UNAUTHORIZED",v[v.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",v[v.FORBIDDEN=403]="FORBIDDEN",v[v.NOT_FOUND=404]="NOT_FOUND",v[v.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",v[v.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",v[v.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",v[v.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",v[v.CONFLICT=409]="CONFLICT",v[v.GONE=410]="GONE",v[v.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",v[v.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",v[v.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",v[v.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",v[v.URI_TOO_LONG=414]="URI_TOO_LONG",v[v.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",v[v.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",v[v.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",v[v.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",v[v.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",v[v.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",v[v.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",v[v.LOCKED=423]="LOCKED",v[v.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",v[v.TOO_EARLY=425]="TOO_EARLY",v[v.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",v[v.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",v[v.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",v[v.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",v[v.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",v[v.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",v[v.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",v[v.BAD_GATEWAY=502]="BAD_GATEWAY",v[v.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",v[v.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",v[v.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",v[v.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",v[v.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",v[v.LOOP_DETECTED=508]="LOOP_DETECTED",v[v.NOT_EXTENDED=510]="NOT_EXTENDED",v[v.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",v))(Ur||{}),wc={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",306:"Switch Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Content Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a teapot",421:"Misdirected Request",422:"Unprocessable Content",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",510:"Not Extended",511:"Network Authentication Required"};var Id={100:"Continue",101:"Switching Protocols",102:"Processing",103:"Early Hints",200:"OK",201:"Created",202:"Accepted",203:"Non-Authoritative Information",204:"No Content",205:"Reset Content",206:"Partial Content",207:"Multi-Status",208:"Already Reported",226:"IM Used",300:"Multiple Choices",301:"Moved Permanently",302:"Found",303:"See Other",304:"Not Modified",305:"Use Proxy",307:"Temporary Redirect",308:"Permanent Redirect",400:"Bad Request",401:"Unauthorized",402:"Payment Required",403:"Forbidden",404:"Not Found",405:"Method Not Allowed",406:"Not Acceptable",407:"Proxy Authentication Required",408:"Request Timeout",409:"Conflict",410:"Gone",411:"Length Required",412:"Precondition Failed",413:"Payload Too Large",414:"URI Too Long",415:"Unsupported Media Type",416:"Range Not Satisfiable",417:"Expectation Failed",418:"I'm a Teapot",421:"Misdirected Request",422:"Unprocessable Entity",423:"Locked",424:"Failed Dependency",425:"Too Early",426:"Upgrade Required",428:"Precondition Required",429:"Too Many Requests",431:"Request Header Fields Too Large",451:"Unavailable For Legal Reasons",500:"Internal Server Error",501:"Not Implemented",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout",505:"HTTP Version Not Supported",506:"Variant Also Negotiates",507:"Insufficient Storage",508:"Loop Detected",509:"Bandwidth Limit Exceeded",510:"Not Extended",511:"Network Authentication Required"},di=Id;function Ed(n){return`${new URL(n.url).pathname}`}s(Ed,"instance");function Td(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=n.headers.get(Mt);return r&&(t.rayId=r),t}s(Td,"trace");var Sd=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Ed(e),trace:Td(e,t),...r},additionalHeaders:o,statusText:di[n.status]}),"merge"),pi=class{static{s(this,"HttpProblemsBase")}static format=s((e,t,r)=>"problem"in e?Dt.format(e,t,r):Dt.format({problem:e},t,r),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:wc[e],...t}}},T=class extends pi{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=Sd(this.getProblemFromStatus(e),t,r,o,i);return Dt.format(a,t,r)}static continue=s((e,t,r,o)=>this.#e(200,e,t,r,o),"continue");static switchingProtocols=s((e,t,r,o)=>this.#e(101,e,t,r,o),"switchingProtocols");static processing=s((e,t,r,o)=>this.#e(102,e,t,r,o),"processing");static earlyHints=s((e,t,r,o)=>this.#e(103,e,t,r,o),"earlyHints");static ok=s((e,t,r,o)=>this.#e(200,e,t,r,o),"ok");static created=s((e,t,r,o)=>this.#e(201,e,t,r,o),"created");static accepted=s((e,t,r,o)=>this.#e(202,e,t,r,o),"accepted");static nonAuthoritativeInformation=s((e,t,r,o)=>this.#e(203,e,t,r,o),"nonAuthoritativeInformation");static noContent=s((e,t,r,o)=>this.#e(204,e,t,r,o),"noContent");static resetContent=s((e,t,r,o)=>this.#e(205,e,t,r,o),"resetContent");static partialContent=s((e,t,r,o)=>this.#e(206,e,t,r,o),"partialContent");static multiStatus=s((e,t,r,o)=>this.#e(207,e,t,r,o),"multiStatus");static alreadyReported=s((e,t,r,o)=>this.#e(208,e,t,r,o),"alreadyReported");static imUsed=s((e,t,r,o)=>this.#e(226,e,t,r,o),"imUsed");static multipleChoices=s((e,t,r,o)=>this.#e(300,e,t,r,o),"multipleChoices");static movedPermanently=s((e,t,r,o)=>this.#e(301,e,t,r,o),"movedPermanently");static found=s((e,t,r,o)=>this.#e(302,e,t,r,o),"found");static seeOther=s((e,t,r,o)=>this.#e(303,e,t,r,o),"seeOther");static notModified=s((e,t,r,o)=>this.#e(304,e,t,r,o),"notModified");static useProxy=s((e,t,r,o)=>this.#e(305,e,t,r,o),"useProxy");static switchProxy=s((e,t,r,o)=>this.#e(306,e,t,r,o),"switchProxy");static temporaryRedirect=s((e,t,r,o)=>this.#e(307,e,t,r,o),"temporaryRedirect");static permanentRedirect=s((e,t,r,o)=>this.#e(308,e,t,r,o),"permanentRedirect");static badRequest=s((e,t,r,o)=>this.#e(400,e,t,r,o),"badRequest");static unauthorized=s((e,t,r,o)=>this.#e(401,e,t,r,o),"unauthorized");static paymentRequired=s((e,t,r,o)=>this.#e(402,e,t,r,o),"paymentRequired");static forbidden=s((e,t,r,o)=>this.#e(403,e,t,r,o),"forbidden");static notFound=s((e,t,r,o)=>this.#e(404,e,t,r,o),"notFound");static methodNotAllowed=s((e,t,r,o)=>this.#e(405,e,t,r,o),"methodNotAllowed");static notAcceptable=s((e,t,r,o)=>this.#e(406,e,t,r,o),"notAcceptable");static proxyAuthenticationRequired=s((e,t,r,o)=>this.#e(407,e,t,r,o),"proxyAuthenticationRequired");static requestTimeout=s((e,t,r,o)=>this.#e(408,e,t,r,o),"requestTimeout");static conflict=s((e,t,r,o)=>this.#e(409,e,t,r,o),"conflict");static gone=s((e,t,r,o)=>this.#e(410,e,t,r,o),"gone");static lengthRequired=s((e,t,r,o)=>this.#e(411,e,t,r,o),"lengthRequired");static preconditionFailed=s((e,t,r,o)=>this.#e(412,e,t,r,o),"preconditionFailed");static contentTooLarge=s((e,t,r,o)=>this.#e(413,e,t,r,o),"contentTooLarge");static uriTooLong=s((e,t,r,o)=>this.#e(414,e,t,r,o),"uriTooLong");static unsupportedMediaType=s((e,t,r,o)=>this.#e(415,e,t,r,o),"unsupportedMediaType");static rangeNotSatisfiable=s((e,t,r,o)=>this.#e(416,e,t,r,o),"rangeNotSatisfiable");static expectationFailed=s((e,t,r,o)=>this.#e(417,e,t,r,o),"expectationFailed");static imATeapot=s((e,t,r,o)=>this.#e(418,e,t,r,o),"imATeapot");static misdirectedRequest=s((e,t,r,o)=>this.#e(421,e,t,r,o),"misdirectedRequest");static unprocessableContent=s((e,t,r,o)=>this.#e(422,e,t,r,o),"unprocessableContent");static locked=s((e,t,r,o)=>this.#e(423,e,t,r,o),"locked");static failedDependency=s((e,t,r,o)=>this.#e(424,e,t,r,o),"failedDependency");static tooEarly=s((e,t,r,o)=>this.#e(425,e,t,r,o),"tooEarly");static upgradeRequired=s((e,t,r,o)=>this.#e(426,e,t,r,o),"upgradeRequired");static preconditionRequired=s((e,t,r,o)=>this.#e(428,e,t,r,o),"preconditionRequired");static tooManyRequests=s((e,t,r,o)=>this.#e(429,e,t,r,o),"tooManyRequests");static requestHeaderFieldsTooLarge=s((e,t,r,o)=>this.#e(431,e,t,r,o),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=s((e,t,r,o)=>this.#e(451,e,t,r,o),"unavailableForLegalReasons");static internalServerError=s((e,t,r,o)=>this.#e(500,e,t,r,o),"internalServerError");static notImplemented=s((e,t,r,o)=>this.#e(501,e,t,r,o),"notImplemented");static badGateway=s((e,t,r,o)=>this.#e(502,e,t,r,o),"badGateway");static serviceUnavailable=s((e,t,r,o)=>this.#e(503,e,t,r,o),"serviceUnavailable");static gatewayTimeout=s((e,t,r,o)=>this.#e(504,e,t,r,o),"gatewayTimeout");static httpVersionNotSupported=s((e,t,r,o)=>this.#e(505,e,t,r,o),"httpVersionNotSupported");static variantAlsoNegotiates=s((e,t,r,o)=>this.#e(506,e,t,r,o),"variantAlsoNegotiates");static insufficientStorage=s((e,t,r,o)=>this.#e(507,e,t,r,o),"insufficientStorage");static loopDetected=s((e,t,r,o)=>this.#e(508,e,t,r,o),"loopDetected");static notExtended=s((e,t,r,o)=>this.#e(510,e,t,r,o),"notExtended");static networkAuthenticationRequired=s((e,t,r,o)=>this.#e(511,e,t,r,o),"networkAuthenticationRequired")};var{toString:Cd}=Object.prototype,{propertyIsEnumerable:Od}=Object.prototype;function mi(n){return Cd.call(n)}s(mi,"toString");function qe(n){return typeof n=="string"}s(qe,"isString");function un(n){return qe(n)&&n!==""}s(un,"isNonEmptyString");function Rc(n){return mi(n)==="[object RegExp]"}s(Rc,"isRegexp");function vc(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Od.call(n,e))]}s(vc,"getOwnEnumerableKeys");function Zt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Zt,"isObject");function fi(n){return typeof n=="number"&&!isNaN(n)}s(fi,"isNumber");function gi(n){return n===!0||n===!1}s(gi,"isBoolean");function xc(n){return typeof n>"u"}s(xc,"isUndefined");function Pc(n){return xc(n)||n===null}s(Pc,"isUndefinedOrNull");function Qn(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Qn,"isErrorLike");var Ic=new Map;function vt(n){if(Array.isArray(n)&&!n.some(o=>typeof o!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new f("Malformed input string");let e=Ic.get(n);if(e)return e;let t=n.split(","),r=[];for(let o of t){let i=o.split("-");if(i.length===2){let a=parseInt(i[0],10),c=parseInt(i[1],10);for(let u=a;u<=c;u++)r.push(u)}else r.push(parseInt(o,10))}return Ic.set(n,r),r}s(vt,"statusCodesStringToNumberArray");function ct(n,e,t){if(!e.startsWith("."))throw new f(`Invalid ${t} - must start with '.' - '${e}' does not`);let r=e.split(".").splice(1),o=n;return r.forEach(i=>{if(o===void 0)throw new k(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(ct,"getValueFromRequestUser");function ut(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new f("Received an array that contains non-string values.");return n}if(qe(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new f(`Expected type of string, received type '${typeof n}'`)}s(ut,"parseValueToStringArray");function Ec(n){if(n==null)return[];if(!Array.isArray(n))throw new f(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!Zt(t))throw new f(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!un(t.name))throw new f("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!fi(t.maxAge))throw new f(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!gi(t.allowCredentials))throw new f("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let r=hi(t,"allowedHeaders"),o=hi(t,"allowedMethods"),i=hi(t,"exposeHeaders"),a;try{a=ut(t.allowedOrigins)}catch(u){throw new f(`Value of 'allowedOrigins' on custom cors policies is invalid. ${u.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:r?r.join(", "):void 0,allowedMethods:o?o.join(", "):void 0,exposeHeaders:i?i.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}s(Ec,"parseCorsPolicies");function hi(n,e){let t;if(n[e]!==void 0)try{t=ut(n[e])}catch(r){throw new f(`Value of '${e}' on custom cors policies is invalid. ${r.message} If using an environment variable, check that it is set correctly.`)}return t}s(hi,"parseOptionalProperty");var Hr=s((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let r=n.map(a=>a.trim().toLowerCase()),o=e.toLowerCase();return r.find(a=>a===o)},"findMatchingOrigin"),Fr=s((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let r=n.allowCredentials;r&&(t["access-control-allow-credentials"]=r);let o=n.maxAge?.toString()??void 0;return o&&(t["access-control-max-age"]=o),t},"generateCorsHeaders");var yi=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,c)=>{let u=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return T.badRequest(a,c,{detail:"Expect headers origin and access-control-request-method"});let m=n.lookup(u,l);if(!m)return T.notFound(a,c);let h=m.routeConfiguration,w=Ad(l,d,p,h,t);return w.isValid?new Response(void 0,{status:200,statusText:"OK",headers:w.headers}):(w.error&&c.log.warn(w.error),T.notFound(a,c))},"optionsHandler"),o=new Te({processors:[ke],handler:r,gateway:e}),i=new xe({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),Ad=s((n,e,t,r,o)=>{let i={isValid:!1,headers:{}};if(r.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(r.corsPolicy==="none")return{...i,error:`No CORS policy set for the route '${r.pathPattern}'`};let a=o?.find(l=>l.name===r.corsPolicy);if(!a)throw new f(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let c=Hr(a.allowedOrigins,t);return c?{isValid:!0,headers:Fr(a,c)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Tc=s((n,e)=>{let t=s(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),r=new Te({processors:[ke],handler:t,gateway:e}),o=new xe({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(o,r.execute)},"registerNoRoutes");var xt=class{static{s(this,"UserRouteConfiguration")}constructor(e){this.path=e.path,this.methods=e.methods,this.label=e.label,this.key=e.key,this.handler=e.handler,this.corsPolicy=e.corsPolicy,this.custom=e.custom,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,this.metadata=e.metadata,this.raw=e.raw}raw;get summary(){return this.raw()?.summary}get operationId(){return this.raw()?.operationId}get tags(){return this.raw()?.tags}get parameters(){return this.raw()?.parameters}get responses(){return this.raw()?.responses}label;key;path;excludeFromOpenApi;pathPattern;metadata;custom;methods;handler;corsPolicy;policies};var _d=new xe({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Sc=s((n,e)=>{let t=s(async(o,i)=>{let a=ai.value?.notFoundHandler;if(a){let c=new URL(o.url);return a(o,i,{get routesMatchedByPathOnly(){return n.lookupByPathOnly(c.pathname).map(l=>l.routeConfiguration).filter(l=>l instanceof xt)}})}return T.notFound(o,i)},"notFoundHandler"),r=new Te({processors:[ke],handler:t,gateway:e});n.addRoute(_d,r.execute)},"registerNotMatchedHandler");var kd=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Cc=s(n=>{kd.forEach(e=>n.delete(e))},"stripCorsHeaders"),jr=s(async(n,e,t,r)=>{let o=e.route;if(!o.corsPolicy||o.corsPolicy==="none"){let d=await r(n),p=new Headers(d.headers);return Cc(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let i=await r(n);if(!(i instanceof Response))throw new ae(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Ld(o,t.routeData.corsPolicies),c=Nd(n,a),u=new Headers(i.headers);return Cc(u),Object.entries(c).forEach(([d,p])=>{u.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:u,webSocket:i.webSocket})},"corsProcessor"),Ld=s((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(r=>r.name===n.corsPolicy);if(t===void 0)throw new f(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Nd=s((n,e)=>{let t=Hr(e.allowedOrigins,n.headers.get("origin"));return t?Fr(e,t):{}},"getCorsHeaders");var bi=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:y.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new Te({processors:[jr],handler:t,gateway:e}),o=new xe({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as Oc,trace as Ac}from"@opentelemetry/api";var lt={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var zr=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!qe(t))throw new k(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ye=class extends zr{static{s(this,"InboundPolicy")}},Pt=class extends zr{static{s(this,"OutboundPolicy")}};var vi=class extends ye{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},xi=class extends Pt{static{s(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t,r){return this.#e(e,t,r,this.options,this.policyName)}},wi=new Map;function Yn(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!wi.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new f(`Invalid state - no Policy with the name '${i}' ${r&&`on route '${r}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let c=a.handler?.module[a.handler.export];if(typeof c!="function")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof c}')`);let u;if(typeof c!="function")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof c}')`);if(c.prototype instanceof ye)u=new c(a.handler.options,a.name);else if(typeof c=="function")u=new vi(c,a.handler.options,a.name);else throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof c}')`);if(typeof u.handler!="function")throw new f(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof u.handler}')`);wi.set(a.name,u)}),t.map(i=>{let a=wi.get(i);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}s(Yn,"getInboundPolicyInstances");var Ri=new Map;function Xn(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.outbound??[],r=n.path),t.filter(i=>!Ri.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new f(`Invalid state - no Policy with the name '${i}' on route '${r}' was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let c=a.handler?.module[a.handler.export],u;if(typeof c!="function")throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof c}')`);if(c.prototype instanceof Pt)u=new c(a.handler.options??{},a.name);else if(typeof c=="function")u=new xi(c,a.handler.options??{},a.name);else throw new f(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof c}')`);if(typeof u.handler!="function")throw new f(`Invalid state - invalid handler on policy '${i}' on route '${r}'`);Ri.set(a.name,u)}),t.map(i=>{let a=Ri.get(i);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}s(Xn,"getOutboundPolicyInstances");var Pi=s(n=>async(e,t)=>{let r=_e.getContextExtensions(t),o=Ac.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{try{let a=[...n],c=e;for(;a.length>0;){let u=a.shift();if(!u)return c;let l=await o.startActiveSpan(`policy:${u.policyName}`,async d=>{let p=await u.handler(c,t);if(p instanceof Request||p instanceof ue||p instanceof Response)return d.end(),p instanceof Response||p instanceof ue?p:new ue(p);{let m=new f(`Invalid state - invalid handler on policy '${u.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Oc.ERROR}),d.recordException(m),m}});if(l instanceof ue)c=l;else if(l instanceof Request)c=new ue(l);else if(l instanceof Response)return l;r.latestRequest=c}return c}finally{i.end()}})},"toStackedInboundHandler"),Ii=s(n=>async(e,t,r)=>{let o=Ac.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{try{let a=[...n],c=e;for(;a.length>0;){let u=a.shift();if(!u)return c;c=await o.startActiveSpan(`policy:${u.policyName}`,async d=>{try{d.setAttribute(lt.PolicyName,u.policyName),d.setAttribute(lt.PolicyType,u.policyType);let p=await u.handler(c,t,r);if(p instanceof Response)return p;{let m=new f(`Invalid state - invalid handler on policy '${u.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Oc.ERROR}),d.recordException(m),m}}finally{d.end()}})}return c}finally{i.end()}})},"toStackedOutboundHandler"),Br=s(async(n,e,t,r)=>{let o=Yn(e.route,t.routeData.policies),i=Xn(e.route,t.routeData.policies);return kc({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function _c({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>kc({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(_c,"createInternalPolicyProcessor");async function kc({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=Pi(t);try{let c=await a(n,e);if(c instanceof Response)return c;let u=await i(c),l=Ii(r),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(u,n,e):d=u.ok?l(u,n,e):u,d}catch(c){return o.errorHandler(n,e,"Error executing policies",c)}}s(kc,"executePolicyProcessor");var Dc=Jl(Mc(),1);function Zc(n,e){try{let t=/v\d+(-\d+)?/g,o=(0,Dc.parse)(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(Zc,"devPortalBaseURL");var qc="/__zuplo/dev-portal",Bd="dev-portal-id",Gd="dev-portal-host",Vd="zp-account",Wd="zp-project",Jd="dev-portal-build",Kd=`
|
|
36
36
|
<!DOCTYPE html>
|
|
37
37
|
<html lang="en">
|
|
38
38
|
<head>
|
|
@@ -55,28 +55,28 @@ import{a as y,b as bt,e as Se,f as Kl,g as Ao,h as _o,i as Ql,j as Yl}from"./chu
|
|
|
55
55
|
</div>
|
|
56
56
|
</body>
|
|
57
57
|
</html>
|
|
58
|
-
`,$c=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=y.instance.deploymentName,o=y.instance.devPortalBaseUrl,i=s(async(u,l)=>{if(y.instance.isLocalDevelopment)return new Response(Kd,{headers:{"content-type":"text/html"}});if(!r)return T.internalServerError(u,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(u.url),p=Zc(o,u.headers),m=new URL(`${d.pathname}${d.search}`,p),{headers:h,method:
|
|
58
|
+
`,$c=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=y.instance.deploymentName,o=y.instance.devPortalBaseUrl,i=s(async(u,l)=>{if(y.instance.isLocalDevelopment)return new Response(Kd,{headers:{"content-type":"text/html"}});if(!r)return T.internalServerError(u,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(u.url),p=Zc(o,u.headers),m=new URL(`${d.pathname}${d.search}`,p),{headers:h,method:w,body:b}=u;return y.instance.build.ACCOUNT_NAME&&h.set(Vd,y.instance.build.ACCOUNT_NAME),y.instance.build.PROJECT_NAME&&h.set(Wd,y.instance.build.PROJECT_NAME),h.set(Bd,r),h.set(Gd,d.host),h.set(Jd,y.instance.build.BUILD_ID),await j.fetch(m.toString(),{headers:h,method:w,body:b,redirect:"manual"})},"devPortalRoute"),a=new Te({processors:[ke,Br],handler:i,gateway:e}),c=new xe({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(c,a.execute)},"registerDevPortalV3Route"),Uc=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=s(async a=>{let c=new URL(a.url);return c.pathname=`${t}${c.pathname.substring(qc.length)}`,Response.redirect(c.toString(),302)},"devPortalRedirectRoute"),o=new Te({processors:[ke],handler:r,gateway:e}),i=new xe({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${qc}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var Ei=0,er=class{static{s(this,"CoreLogger")}constructor(e,t,r,o,i){this.#n=t,this.#r=r??"local",this.#o=o,this.#i=i,this.#e(e)}#e=s(e=>{let t=["error","warn","info","debug"],r=!1,o=s(()=>{},"emptyFunction"),i=s((a,c)=>{this.#i.forEach(u=>{u.log(a,c)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:i,a==e&&(r=!0)})},"#setupMethods");#t={};#n;#r;#o;#i;log(e,t,r,o,i,a){Ei>=Number.MAX_SAFE_INTEGER&&(Ei=0);let c={logId:crypto.randomUUID(),requestId:r,rayId:o,level:e,logSource:t,messages:i,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Ei++};this.#t[e](c,a)}};var Re=class extends Rt{static{s(this,"LogPlugin")}};var Vr=class{static{s(this,"LoggingContext")}constructor(e,t,r,o){this.#e=e,this.custom=t,this.originalRequest=r,this.route=o}#e;custom;originalRequest;route;waitUntil=s(e=>{this.#e.waitUntil(e)},"waitUntil")};var tr=class{static{s(this,"RequestLogger")}constructor(e,t,r,o){this.#t=e,this.#n=t,this.#r=r,this.#o=o}#e="request";#t;#n;#r;#o;debug=s((...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)},"debug");info=s((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"info");log=s((...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)},"log");warn=s((...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)},"warn");error=s((...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)},"error")};var Qd=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Yd=new Map(Qd);var Xd=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Ti=Symbol(".toJSON was called"),ep=s(n=>{n[Ti]=!0;let e=n.toJSON();return delete n[Ti],e},"toJSON"),tp=s(n=>Yd.get(n)??Error,"getErrorConstructor"),Hc=s(({from:n,seen:e,to:t,forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:c})=>{if(!t)if(Array.isArray(n))t=[];else if(!c&&Qn(n)){let l=tp(n.name);t=new l}else t={};if(e.push(n),i>=o)return t;if(a&&typeof n.toJSON=="function"&&n[Ti]!==!0)return ep(n);let u=s(l=>Hc({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:c}),"continueDestroyCircular");for(let[l,d]of Object.entries(n)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){t[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){t[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){t[l]=d;continue}if(!e.includes(n[l])){i++,t[l]=u(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:d}of Xd)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Qn(n[l])?u(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function qt(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Hc({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}s(qt,"serializeError");var np=/file:\/\/\/(.*?)\/dist\//g,rp="at async Event.respondWith";function Si(n){return typeof n!="string"?n:n.split(`
|
|
59
59
|
`).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(np,"").replaceAll(rp,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
|
|
60
60
|
`)}s(Si,"cleanStack");function Wr(n,e,t=""){let r=[],o=e?.maxDepth??3;return s(function i(a,c={},u,l){let d=c.indent||" ",p;c.inlineCharacterLimit===void 0?p={newline:`
|
|
61
61
|
`,newlineOrSpace:`
|
|
62
|
-
`,pad:u,indent:u+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let m=s(h=>{if(c.inlineCharacterLimit===void 0)return h;let
|
|
63
|
-
`).replace(new RegExp(p.pad,"g"),u).replace(new RegExp(p.indent,"g"),u+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||Rc(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let h="["+p.newline+a.map((
|
|
62
|
+
`,pad:u,indent:u+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let m=s(h=>{if(c.inlineCharacterLimit===void 0)return h;let w=h.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return w.length<=c.inlineCharacterLimit?w:h.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
|
|
63
|
+
`).replace(new RegExp(p.pad,"g"),u).replace(new RegExp(p.indent,"g"),u+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||Rc(a))return String(a);if(a instanceof Date)return`new Date('${a.toISOString()}')`;if(l>o)return"...";if(Array.isArray(a)){if(a.length===0)return"[]";r.push(a);let h="["+p.newline+a.map((w,b)=>{let P=a.length-1===b?p.newline:","+p.newlineOrSpace,N=i(w,c,u+d,l+1);return c.transform&&(N=c.transform(a,b,N)),p.indent+N+P}).join("")+p.pad+"]";return r.pop(),m(h)}if(Zt(a)){let h=vc(a);if(c.filter&&(h=h.filter(b=>c.filter?.(a,b))),h.length===0)return"{}";r.push(a);let w="{"+p.newline+h.map((b,P)=>{let N=h.length-1===P?p.newline:","+p.newlineOrSpace,A=typeof b=="symbol",B=!A&&/^[a-z$_][$\w]*$/i.test(b),$=A||B?b:i(b,c,"",l+1),G=i(a[b],c,u+d,l+1);return c.transform&&(G=c.transform(a,b,G)),p.indent+String($)+": "+G+N}).join("")+p.pad+"}";return r.pop(),m(w)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,h=>h===`
|
|
64
64
|
`?"\\n":"\\r"),c.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}s(Wr,"stringifyObject");function $e(n){return jc(qt(n))}s($e,"serializeMessage");function nt(n){return n.map(e=>$e(e))}s(nt,"serializeMessages");function ln(n){if(n.length===0)return"<no data provided to log>";let e=n[0];return typeof e=="string"?e:e instanceof Error?e.message:jc(qt(e))}s(ln,"extractBestMessage");function Fc(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Qn(t))if(t.stack)e.push(t.stack);else{let r=Wr(qt(t));e.push(r)}else if(typeof t=="object"){let r=Wr(t);e.push(r)}else{let r=Ci(t);e.push(r)}}),e.join(`
|
|
65
|
-
`)}s(Fc,"messagesToMultilineText");function jc(n){return typeof n=="string"?n:JSON.stringify(n)}s(jc,"stringifyNonString");function Ci(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?mi(n):"unknown"}s(Ci,"stringifyNonStringToText");import{SignJWT as op,importPKCS8 as ip}from"jose";async function Oe(n,e,t){for(let r=0;r<=n.retries;r++){let o=j.fetch(e,t);if(r===n.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new f("An unknown error occurred, ensure retries is not negative")}s(Oe,"fetchRetry");async function Be({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new op(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(Be,"getTokenFromGcpServiceAccount");async function zc(n,e,t){if(!n.startsWith("projects/"))throw new f(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Oi("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}s(zc,"exchangeIDTokenForGcpWorkloadToken");async function Bc({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return Vc(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}s(Bc,"generateServiceAccountIDToken");async function Gc(n,e,t){return Oi(n,{token:e,returnSecureToken:!0},t)}s(Gc,"exchangeFirebaseJwtForIdToken");async function dn(n,e,t){return Oi(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(dn,"exchangeGgpJwtForIdToken");async function Oi(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return Vc(n,r,t)}s(Oi,"fetchTokenFromBody");async function Vc(n,e,t){let r=await Oe(t,n,e);if(r.status!==200){let i;try{let a=await r.text(),c=JSON.parse(a);i={cause:c.error_description??c.error??c}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Vc,"fetchToken");var Le=class n{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await ip(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var sp={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Wc=s(n=>e=>{let t={};return t.accountName=n.build.ACCOUNT_NAME,t.projectName=n.build.PROJECT_NAME,t.deploymentName=n.deploymentName,t.environmentType=n.loggingEnvironmentStage,t.labels={requestId:e.requestId,source:e.logSource,logOwner:e.logOwner},t.rayId=e.rayId??"",t.runtime={buildId:n.build.BUILD_ID,buildTimestamp:n.build.TIMESTAMP,gitSHA:n.build.GIT_SHA,version:n.build.ZUPLO_VERSION},t.atomicCounter=e.vectorClock,{logId:e.logId,timestamp:e.timestamp,observerdTimestamp:e.timestamp,traceId:e.requestId,severityText:e.level,severityNumber:sp[e.level],body:nt(e.messages),attributes:t}},"unifiedFormatter");async function se(n,e){if(n.level==="error"&&console.error(n.messages),!y.instance.remoteLogURL||!y.instance.loggingId||!y.instance.remoteLogToken)return;let t;try{t=await e?.text()}catch{}try{let r={...n,messages:[...n.messages,...t?[t]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:y.instance.build.BUILD_ID,loggingId:y.instance.loggingId,vectorClock:0};await Jc(y.instance,[r])}catch(r){console.error(r)}}s(se,"sendRemoteGlobalLog");async function Jc(n,e){let t=Wc(n);try{let r=new Headers({"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`});Xe(r),await j.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json","user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}s(Jc,"sendLogs");var ap=s(n=>async e=>{e.length!==0&&await Jc(n,e)},"dispatchFunction"),Jr,nr=class{static{s(this,"UnifiedLogTransport")}constructor(e){Jr||(Jr=new ie("unified-log-transport",1,ap(e)))}log(e,t){Jr.enqueue(e),t.waitUntil(Jr.waitUntilFlushed())}};var Ai=class extends Re{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new rr(this.options)}},cp="https://logging.googleapis.com/v2/entries:write?alt=json",_i={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},rr=class{static{s(this,"GoogleLogTransport")}constructor(e){g("logging.google-cloud"),this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;async init(){this.#t=await Le.init(this.#e)}log(e,t){if(!this.#t)throw new ae("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r=Object.assign({allMessages:nt(e.messages)},this.#s),o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:_i[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=ln(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length===0)return;this.#t||(this.#t=await Le.init(this.#e));let t=await Be({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await j.fetch(cp,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||await se({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`]},r)}catch{await se({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new ie("google-log-transport",1,this.dispatchFunction)};var Kr="gcp";function Qr(n){let e={allMessages:nt(n.messages)},t="zuplo-production",r=ln(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:_i[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}s(Qr,"gcpLogFormat");var or=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===Kr){if(e.messages.length===0)return;this.#e[e.level](Qr(e))}else{let r={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:nt(e.messages)};this.#e[e.level](JSON.stringify(r))}}};var Mi=class extends Re{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new ir(this.options)}},ki="__ddtags",Li="__ddattr",Ni=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),up=s(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Ni(r)):t.push(`${Ni(r)}:${Ni(o.toString())}`)}),t.join(",")},"formatTags"),ir=class{static{s(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.tags??{},this.#a=e.source??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=Object.assign({},this.#s),o={},i=[...e.messages];if(!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization){let l=t.custom[ki];l&&typeof l=="object"&&(g("logging.datadog.legacy-tags"),Object.assign(r,l));let d=e.messages.findIndex(h=>h[ki]!==void 0);d>-1&&(Object.assign(r,i[d][ki]),i.splice(d,1));let p=t.custom[Li];p&&typeof p=="object"&&(g("logging.datadog.legacy-attributes"),Object.assign(o,p));let m=e.messages.findIndex(h=>h[Li]!==void 0);m>-1&&(Object.assign(o,i[m][Li]),i.splice(m,1))}let a=nt(i),c={...e,activityId:e.requestId,trace:e.requestId},u=Object.assign({message:{...c,messages:a},ddsource:this.#a,hostname:new URL(t.originalRequest.url).hostname,msg:ln(a),atomic_counter:e.vectorClock,service:e.loggingId,ddtags:up(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o,ray_id:e.rayId,request_id:e.requestId},this.#i,o);this.batcher.enqueue(u),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let t=await j.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});t.ok||await se({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`]},t)}catch{await se({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new ie("data-dog-transport",10,this.dispatchFunction)};var sr=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Kr){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Qr(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var Di=Ce("zuplo:logging"),Yr=class n{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(y.instance,e),r=await n.setupUserCoreLogger(y.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Di("Gateway.setupSystemCoreLogger");let o=[],i=t.getService(Lr);return i?o.push(new sr(i.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new or(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new nr(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new er(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Di("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=t.getService(Lr);if(a&&a.captureUserLogs===!0?r.push(new sr(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new or(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new nr(e)),!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization&&(o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),r.push(new rr({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY)){g("logging.datadog.legacy-initialization");let c=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new ir({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:c}))}return at.forEach(c=>{c instanceof Re&&r.push(c.getTransport())}),await Promise.all(r.map(async c=>{c.init&&await c.init()})),new er(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i,a){Di("Gateway.createRequestLoggers");let c=new Vr(r,o,i,a),u=new tr(e,t,this.systemCoreLogger,c);return{userRequestLogger:new tr(e,t,this.userCoreLogger,c),systemRequestLogger:u}}};var pn=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Xr=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}};var Zi=class{static{s(this,"UrlPatternRouterEntry")}constructor(e,t,r){this.fullPath=e,this.config=t,this.executableHandler=r;try{this.urlPattern=new URLPattern({pathname:this.fullPath})}catch(o){throw new ae(`Invalid path '${e}'. ${o.message}`)}}urlPattern;fullPath;config;executableHandler},eo=class{static{s(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof xt||e instanceof xe))throw new ae("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r;"pathPattern"in e&&e.pathPattern?r=e.pathPattern:r=e.path;try{let o=new Zi(r,e,t);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new Xr(`addRoute-error: Invalid path '${r}'. '${o.message}'`,{cause:o})}}lookup(e,t){if(typeof t>"u")throw new f(`Invalid request - Method was undefined. Path: '${e}'`);for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r];if(o.config.methods.includes(t)){let i=o.urlPattern.exec({pathname:e});if(i!==null)return new pn(o.config,o.executableHandler,i.pathname.groups)}}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],i=o.urlPattern.exec({pathname:e});if(i!==null){let a=new pn(o.config,o.executableHandler,i.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as lp}from"node:async_hooks";var to={context:new lp};var qi;function Kc(n){qi=n}s(Kc,"setGlobalZuploEventContext");function It(){if(qi===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return qi}s(It,"getGlobalZuploEventContext");function Qc({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);ac.includes(o.toLowerCase())&&!cc.includes(r.toLowerCase())&&t.delete(r)}t.delete(Qa)}else sc.forEach(r=>{t.delete(r)});return t}s(Qc,"normalizeIncomingRequestHeaders");var Et=Ce("zuplo:runtime"),Ie=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Et("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Et("Gateway.initialize"),!n.#e){let i=await Yr.init(r),a=await e(),c={...a,corsPolicies:Ec(a.corsPolicies)},u=new n(c,t,i,o);n.#e=u}if(!n.#e)throw new ae("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Et("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new ae("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Br,jr,ke];setupRoutes=s(()=>{Et("Gateway.setupRoutes");let e=this.routeData,t=new eo;if(e.routes.length===0)return li(t,this),bi(t,this),yi(t,this),Tc(t,this),t;let{enabled:r,version:o}=this.runtimeSettings.developerPortal;r&&o==="legacy"&&(Uc(t,this),$c(t,this)),li(t,this),bi(t,this),yi(t,this);for(let i of at)i instanceof Ee&&i.registerRoutes(t,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new f(`Invalid state - No handler on route for path '${i.path}'`);let c=new Te({processors:this.#r,handler:a,gateway:this}),u=new xt(i);t.addRoute(u,c.execute)}),Sc(t,this),t},"setupRoutes");errorHandler(e,t,r,o){Et("Gateway.internalErrorResponse"),t.log.error(r,o);let i={};if(y.instance.isLocalDevelopment||y.instance.isWorkingCopy)if(o instanceof k&&o.extensionMembers)i=o.extensionMembers;else if(o.cause){let a=qt(o.cause);"stack"in a&&(a.stack=Si(a.stack)),i={cause:a}}else{let a=qt(o);"stack"in a&&(a.stack=Si(a.stack)),i={cause:a}}return T.internalServerError(e,t,{detail:o.message,...i})}async handleRequest(e,t,r){let o=e.headers.get(an)??e.headers.get(Ka)??r?.parentContext?.requestId??crypto.randomUUID(),i=e.headers.get(Mt);Kc(t);let a=Qc({headers:e.headers,removeAllVendorHeadersExceptListed:y.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(an,o);let c=new Request(e,{headers:a});if(["GET","HEAD"].includes(c.method)&&c.body){let B=new Headers(c.headers);B.set(Vo,"true"),c=new Request(c,{headers:B,body:null})}c=await hc(c);let u=new URL(c.url),l=u.pathname,d=this.#n.lookup(l,c.method);if(!d)throw new ae(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p={},{userRequestLogger:m,systemRequestLogger:h}=this.#t.createRequestLoggers(o,i,t,p,c,d.routeConfiguration);cn(u)||m.debug(`Request received '${u.pathname}'`,{method:c.method,url:u.pathname,hostname:u.hostname,route:d.routeConfiguration.path});let x=new no(e.headers),b=new ue(c,{params:d.params}),P=new ro({logger:m,route:d.routeConfiguration,requestId:o,event:t,custom:p,incomingRequestProperties:x,parentContext:r?.parentContext}),N=to.context.getStore();N&&(N.context=P);let A=d.routeConfiguration.raw();dp.getActiveSpan()?.setAttributes({"http.route":P.route.path??P.route.pathPattern,"cloud.region":P.incomingRequestProperties.colo,[lt.RoutePathPattern]:P.route.pathPattern,[lt.RouteOperationId]:A.operationId,[lt.RouteTrace]:A["x-zuplo-trace"],[lt.RouteSystem]:cn(u)?!0:void 0}),_e.initialize(P,b);try{if(ne.addLogger(P,h),y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!cn(u):!u.pathname.startsWith("/__zuplo")){let O=await mc(b,P);if(O instanceof Response)return O;{let F=_e.getContextExtensions(P);b=O,F.latestRequest=b}}let B=d.executableHandler;pp(B,d,c),Et("Gateway.handleRequest - call user handler");let $=await B(b,P);if(Et("Gateway.handleRequest - user handler"),!($ instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof $}`);if($.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let G;if($.headers.get(an)===null&&!$.webSocket){let O=new Headers($.headers);O.set(an,o),G=new Response($.body,{status:$.status,statusText:$.statusText,headers:O,cf:$.cf})}else G=$;return G}catch(B){return B instanceof k?(m.error(B),h.warn(B)):h.error(B),await this.errorHandler(b,P,"Error executing handler",B)}}};function pp(n,e,t){if(Et("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new f(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new f(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}s(pp,"checkHandler");import{SpanStatusCode as Yc,trace as Xc}from"@opentelemetry/api";var eu=s(async(n,e,t)=>{let r=Ie.instance.routeData.policies,o=Yn([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);let i=o[0];return await Xc.getTracer("pipeline").startActiveSpan(`policy:${i.policyName}`,async u=>{try{let l=await i.handler(e,t);if(l instanceof Request||l instanceof ue||l instanceof Response)return l instanceof Response||l instanceof ue?l:new ue(l);{let d=new f(`Invalid state - invalid handler on policy '${i.policyName}' invoked via 'invokeInboundPolicy' on route '${t.route.path}'. The result of an inbound policy must be a Response or Request.`);throw u.setStatus({code:Yc.ERROR}),u.recordException(d),d}}finally{u.end()}})},"invokeInboundPolicy"),tu=s(async(n,e,t,r)=>{let o=Ie.instance.routeData.policies,i=Xn([n],o);if(i.length===0)throw new k(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);let a=i[0];return await Xc.getTracer("pipeline").startActiveSpan(`policy:${a.policyName}`,async l=>{try{let d=await a.handler(e,t,r);if(d instanceof Response)return d;{let p=new f(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw l.setStatus({code:Yc.ERROR}),l.recordException(p),p}}finally{l.end()}})},"invokeOutboundPolicy");function mp(n){let e={};if(!n)return e;try{let t=n.split(","),r={};return t.forEach(o=>{let[i,a]=o.split("=");i&&a&&(r[i.trim()]=a.trim())}),r.asnum&&(e[Un]=r.asnum),r.zip&&(e[Hn]=r.zip.split("+")[0]),r.dma&&(e[Fn]=r.dma),r.region_code&&(e[jn]=r.region_code),r.timezone&&(e[zn]=r.timezone),r.city&&(e[Cr]=r.city),r.continent&&(e[Or]=r.continent),r.country_code&&(e[Ar]=r.country_code),r.long&&(e[_r]=r.long),r.lat&&(e[kr]=r.lat),e}catch{return{}}}s(mp,"parseEdgeScapeHeader");function nu(n,e){let t=mp(e);for(let[r,o]of Object.entries(t))n.has(r)||n.set(r,o)}s(nu,"setZpHeadersFromAkamaiEdgeScapeHeader");var no=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let t=e.get(ni);if(t){let r=new Headers(e);nu(r,t),this.#e=r}}get asn(){try{let e=this.#e.get(Un);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Xo)??void 0}get city(){return this.#e.get(Wo)??this.#e.get(Cr)??void 0}get continent(){return this.#e.get(Jo)??this.#e.get(Or)??void 0}get country(){return this.#e.get(Ko)??this.#e.get(Ar)??void 0}get latitude(){return this.#e.get(Yo)??this.#e.get(kr)??void 0}get longitude(){return this.#e.get(Qo)??this.#e.get(_r)??void 0}get colo(){return this.#e.get(ei)??void 0}get postalCode(){return this.#e.get(tc)??this.#e.get(Hn)??void 0}get metroCode(){return this.#e.get(ec)??this.#e.get(Fn)??void 0}get region(){return this.#e.get(Ya)??this.#e.get(ti)??void 0}get regionCode(){return this.#e.get(Xa)??this.#e.get(jn)??void 0}get timezone(){return this.#e.get(nc)??this.#e.get(zn)??void 0}get httpProtocol(){return this.#e.get(ic)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone,httpProtocol:this.httpProtocol}}};function Tt(n){return{contextId:n.contextId,incomingRequestProperties:n.incomingRequestProperties,requestId:n.requestId,route:n.route,custom:n.custom,parentContext:n.parentContext}}s(Tt,"createRewriteContext");var Jn=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Kn=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},_e=class n{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;#t;#n;#r;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[],this.#r=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#r.push(e)}onResponseSendingFinal=s(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=s(async(e,t,r)=>{let o=e;for(let i of this.#n)o=await i(e,t,r);return o},"onResponseSending");onHandlerResponse=s(async(e,t,r)=>{for(let o of this.#r)await o(e,t,r)},"onHandlerResponse")},ro=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:i,incomingRequestProperties:a,parentContext:c}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.parentContext=c,this.#e=o,this.invokeInboundPolicy=(u,l)=>eu(u,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,l,d)=>tu(u,l,d,this),this.invokeRoute=async(u,l)=>{let d=u;typeof u=="string"&&u.startsWith("/")&&(d=new URL(u,"http://localhost"));let p=new ue(d,l);return Ie.instance.handleRequest(p,this,{parentContext:this})},this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{_e.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{_e.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=s(i=>{try{typeof t=="function"?t(i):t.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var fp="Error initializing gateway. Check your configuration for errors or contact support.",gp="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",$i=class{constructor(e,t,r,o,i,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=i;this.runtimeInit=a}static{s(this,"Handler")}requestHandler=s(async(e,t,r)=>{y.initialize({build:this.buildEnvironment,runtime:t});try{await yc(this.runtimeInit)}catch(i){this.handleError(i,gp,e)}return dc(s(async(i,a)=>{let c;try{c=await Ie.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,fp,i)}let u={context:void 0};return to.context.run(u,async()=>c.handleRequest(i,a))},"innerHandler"))(e,r)},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof f&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:y.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function hp(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",i=t+1;i<n.length;){var a=n.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=i;continue}if(r==="("){var c=1,u="",i=t+1;if(n[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<n.length;){if(n[i]==="\\"){u+=n[i++]+n[i++];continue}if(n[i]===")"){if(c--,c===0){i++;break}}else if(n[i]==="("&&(c++,n[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));u+=n[i++]}if(c)throw new TypeError("Unbalanced pattern at ".concat(t));if(!u)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:u}),t=i;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}s(hp,"lexer");function Hi(n,e){e===void 0&&(e={});for(var t=hp(n),r=e.prefixes,o=r===void 0?"./":r,i=e.delimiter,a=i===void 0?"/#?":i,c=[],u=0,l=0,d="",p=s(function(V){if(l<t.length&&t[l].type===V)return t[l++].value},"tryConsume"),m=s(function(V){var S=p(V);if(S!==void 0)return S;var E=t[l],U=E.type,we=E.index;throw new TypeError("Unexpected ".concat(U," at ").concat(we,", expected ").concat(V))},"mustConsume"),h=s(function(){for(var V="",S;S=p("CHAR")||p("ESCAPED_CHAR");)V+=S;return V},"consumeText"),x=s(function(V){for(var S=0,E=a;S<E.length;S++){var U=E[S];if(V.indexOf(U)>-1)return!0}return!1},"isSafe"),b=s(function(V){var S=c[c.length-1],E=V||(S&&typeof S=="string"?S:"");if(S&&!E)throw new TypeError('Must have text between two parameters, missing text after "'.concat(S.name,'"'));return!E||x(E)?"[^".concat(Ui(a),"]+?"):"(?:(?!".concat(Ui(E),")[^").concat(Ui(a),"])+?")},"safePattern");l<t.length;){var P=p("CHAR"),N=p("NAME"),A=p("PATTERN");if(N||A){var B=P||"";o.indexOf(B)===-1&&(d+=B,B=""),d&&(c.push(d),d=""),c.push({name:N||u++,prefix:B,suffix:"",pattern:A||b(B),modifier:p("MODIFIER")||""});continue}var $=P||p("ESCAPED_CHAR");if($){d+=$;continue}d&&(c.push(d),d="");var G=p("OPEN");if(G){var B=h(),O=p("NAME")||"",F=p("PATTERN")||"",Y=h();m("CLOSE"),c.push({name:O||(F?u++:""),pattern:O&&!F?b(B):F,prefix:B,suffix:Y,modifier:p("MODIFIER")||""});continue}m("END")}return c}s(Hi,"parse");function ru(n,e){return yp(Hi(n,e),e)}s(ru,"compile");function yp(n,e){e===void 0&&(e={});var t=bp(e),r=e.encode,o=r===void 0?function(u){return u}:r,i=e.validate,a=i===void 0?!0:i,c=n.map(function(u){if(typeof u=="object")return new RegExp("^(?:".concat(u.pattern,")$"),t)});return function(u){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=u?u[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",x=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!x)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var P=o(m[b],p);if(a&&!c[d].test(P))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var P=o(String(m),p);if(a&&!c[d].test(P))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix;continue}if(!h){var N=x?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}s(yp,"tokensToFunction");function Ui(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(Ui,"escapeString");function bp(n){return n&&n.sensitive?"":"i"}s(bp,"flags");var wp=Ce("zuplo:runtime"),ji=new TextEncoder,ou={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},Rp=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],mn=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:i,cache:a,retries:c,initRetryMs:u}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=c??0,this.initRetryMs=u||50}async sign(e,t){let r=new zi(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){wp("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,t),a=j.fetch(o,i);if(r===this.retries)return a;let c=await a;if(c.status<500&&c.status!==429)return c;await new Promise(u=>setTimeout(u,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new f("An unknown error occurred, ensure retries is not negative")}},zi=class{static{s(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:c,service:u,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:h,allHeaders:x,singleEncode:b}){if(t==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=c;let P,N;(!u||!l)&&([P,N]=vp(this.url,this.headers)),this.service=u||P||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let A=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter($=>x||!Rp.includes($)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map($=>$+":"+($==="host"?this.url.host:(this.headers.get($)||"").replace(/\s+/g," "))).join(`
|
|
65
|
+
`)}s(Fc,"messagesToMultilineText");function jc(n){return typeof n=="string"?n:JSON.stringify(n)}s(jc,"stringifyNonString");function Ci(n){return typeof n=="string"?n:n===null?"null":typeof n>"u"?"undefined":typeof n=="number"||typeof n=="boolean"||typeof n=="bigint"||typeof n=="symbol"?n.toString():typeof n=="function"?`[function ${n.name}]`:typeof n=="object"&&Array.isArray(n)?`[array ${n.length}]`:n instanceof Error?`${n.name??"Error"}: ${n.message??"unknown"}`:typeof n=="object"?mi(n):"unknown"}s(Ci,"stringifyNonStringToText");import{SignJWT as op,importPKCS8 as ip}from"jose";async function Oe(n,e,t){for(let r=0;r<=n.retries;r++){let o=j.fetch(e,t);if(r===n.retries)return o;let i=await o;if(i.status<500&&i.status!==429)return i;n?.logger?.error("Request failed, retrying",{method:typeof e=="string"?"GET":e.method,url:typeof e=="string"?e:e.url,status:i.status}),await new Promise(a=>setTimeout(a,n.retryDelayMs*Math.pow(2,r)))}throw new f("An unknown error occurred, ensure retries is not negative")}s(Oe,"fetchRetry");async function Be({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new op(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(Be,"getTokenFromGcpServiceAccount");async function zc(n,e,t){if(!n.startsWith("projects/"))throw new f(`The provided audience is invalid: ${n}. It must start with 'projects/'.`);return Oi("https://sts.googleapis.com/v1/token",{audience:`//iam.googleapis.com/${n}`,grant_type:"urn:ietf:params:oauth:grant-type:token-exchange",subject_token_type:"urn:ietf:params:oauth:token-type:jwt",requested_token_type:"urn:ietf:params:oauth:token-type:access_token",subject_token:e,scope:"https://www.googleapis.com/auth/cloud-platform"},t)}s(zc,"exchangeIDTokenForGcpWorkloadToken");async function Bc({serviceAccountEmailOrIdentifier:n,audience:e,accessToken:t},r){let o={audience:e,includeEmail:!0};return Vc(`https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${encodeURIComponent(n)}:generateIdToken`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},redirect:"follow",body:JSON.stringify(o)},r)}s(Bc,"generateServiceAccountIDToken");async function Gc(n,e,t){return Oi(n,{token:e,returnSecureToken:!0},t)}s(Gc,"exchangeFirebaseJwtForIdToken");async function dn(n,e,t){return Oi(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(dn,"exchangeGgpJwtForIdToken");async function Oi(n,e,t){let r={method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)};return Vc(n,r,t)}s(Oi,"fetchTokenFromBody");async function Vc(n,e,t){let r=await Oe(t,n,e);if(r.status!==200){let i;try{let a=await r.text(),c=JSON.parse(a);i={cause:c.error_description??c.error??c}}catch{}throw new k({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Vc,"fetchToken");var Le=class n{static{s(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:e,privateKey:t}){this.#t=e,this.#e=t}static async init(e){let t=JSON.parse(e),r=await ip(t.private_key.trim(),"RS256");return new n({serviceAccount:t,privateKey:r})}get type(){return this.#t.type}get projectId(){return this.#t.project_id}get privateKeyId(){return this.#t.private_key_id}get privateKey(){return this.#e}get clientEmail(){return this.#t.client_email}get clientId(){return this.#t.client_id}get authUri(){return this.#t.auth_uri}get tokenUrl(){return this.#t.token_url}get authProviderX509CertUrl(){return this.#t.auth_provider_x509_cert_url}get clientX509CertUrl(){return this.#t.client_x509_cert_url}get universalDomain(){return this.#t.universe_domain}};var sp={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Wc=s(n=>e=>{let t={};return t.accountName=n.build.ACCOUNT_NAME,t.projectName=n.build.PROJECT_NAME,t.deploymentName=n.deploymentName,t.environmentType=n.loggingEnvironmentStage,t.labels={requestId:e.requestId,source:e.logSource,logOwner:e.logOwner},t.rayId=e.rayId??"",t.runtime={buildId:n.build.BUILD_ID,buildTimestamp:n.build.TIMESTAMP,gitSHA:n.build.GIT_SHA,version:n.build.ZUPLO_VERSION},t.atomicCounter=e.vectorClock,{logId:e.logId,timestamp:e.timestamp,observerdTimestamp:e.timestamp,traceId:e.requestId,severityText:e.level,severityNumber:sp[e.level],body:nt(e.messages),attributes:t}},"unifiedFormatter");async function se(n,e){if(n.level==="error"&&console.error(n.messages),!y.instance.remoteLogURL||!y.instance.loggingId||!y.instance.remoteLogToken)return;let t;try{t=await e?.text()}catch{}try{let r={...n,messages:[...n.messages,...t?[t]:[]],logId:crypto.randomUUID(),logOwner:"user",logSource:"runtime",rayId:null,requestId:`global-${crypto.randomUUID()}`,timestamp:new Date,buildId:y.instance.build.BUILD_ID,loggingId:y.instance.loggingId,vectorClock:0};await Jc(y.instance,[r])}catch(r){console.error(r)}}s(se,"sendRemoteGlobalLog");async function Jc(n,e){let t=Wc(n);try{let r=new Headers({"content-type":"application/json",authentication:`Bearer ${n.remoteLogToken}`});Xe(r),await j.fetch(`${n.remoteLogURL}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:e.map(t)}),headers:{"content-type":"application/json","user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(r){console.error(r)}}s(Jc,"sendLogs");var ap=s(n=>async e=>{e.length!==0&&await Jc(n,e)},"dispatchFunction"),Jr,nr=class{static{s(this,"UnifiedLogTransport")}constructor(e){Jr||(Jr=new ie("unified-log-transport",1,ap(e)))}log(e,t){Jr.enqueue(e),t.waitUntil(Jr.waitUntilFlushed())}};var Ai=class extends Re{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new rr(this.options)}},cp="https://logging.googleapis.com/v2/entries:write?alt=json",_i={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},rr=class{static{s(this,"GoogleLogTransport")}constructor(e){g("logging.google-cloud"),this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;async init(){this.#t=await Le.init(this.#e)}log(e,t){if(!this.#t)throw new ae("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r=Object.assign({allMessages:nt(e.messages)},this.#s),o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:_i[e.level],timestamp:e.timestamp,trace:`projects/${o}/traces/${e.requestId}`,labels:{requestId:e.requestId,buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner,environment:this.#r,environmentType:this.#o,environmentStage:this.#i}};e.rayId&&(i.labels.rayId=e.rayId);let a=ln(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length===0)return;this.#t||(this.#t=await Le.init(this.#e));let t=await Be({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"});try{let r=await j.fetch(cp,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||await se({level:"error",messages:[`Failed to send logs to Google: ${r.status} - ${r.statusText}`]},r)}catch{await se({level:"error",messages:["Failed to connect to Google logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new ie("google-log-transport",1,this.dispatchFunction)};var Kr="gcp";function Qr(n){let e={allMessages:nt(n.messages)},t="zuplo-production",r=ln(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:_i[n.level],timestamp:n.timestamp,"logging.googleapis.com/labels":{buildId:n.buildId,source:n.logSource,loggingId:n.loggingId,logOwner:n.logOwner},"logging.googleapis.com/trace":`projects/${t}/traces/${n.requestId}`,allMessages:e.allMessages};return n.rayId&&(o["logging.googleapis.com/labels"].rayId=n.rayId),o}s(Qr,"gcpLogFormat");var or=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e,t){if(this.#t===Kr){if(e.messages.length===0)return;this.#e[e.level](Qr(e))}else{let r={...e,url:t.originalRequest.url,method:t.originalRequest.method,route:t.route.pathPattern??t.route.path,messages:nt(e.messages)};this.#e[e.level](JSON.stringify(r))}}};var Mi=class extends Re{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new ir(this.options)}},ki="__ddtags",Li="__ddattr",Ni=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),up=s(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Ni(r)):t.push(`${Ni(r)}:${Ni(o.toString())}`)}),t.join(",")},"formatTags"),ir=class{static{s(this,"DataDogTransport")}constructor(e){g("logging.datadog"),this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.tags??{},this.#a=e.source??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=Object.assign({},this.#s),o={},i=[...e.messages];if(!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization){let l=t.custom[ki];l&&typeof l=="object"&&(g("logging.datadog.legacy-tags"),Object.assign(r,l));let d=e.messages.findIndex(h=>h[ki]!==void 0);d>-1&&(Object.assign(r,i[d][ki]),i.splice(d,1));let p=t.custom[Li];p&&typeof p=="object"&&(g("logging.datadog.legacy-attributes"),Object.assign(o,p));let m=e.messages.findIndex(h=>h[Li]!==void 0);m>-1&&(Object.assign(o,i[m][Li]),i.splice(m,1))}let a=nt(i),c={...e,activityId:e.requestId,trace:e.requestId},u=Object.assign({message:{...c,messages:a},ddsource:this.#a,hostname:new URL(t.originalRequest.url).hostname,msg:ln(a),atomic_counter:e.vectorClock,service:e.loggingId,ddtags:up(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o,ray_id:e.rayId,request_id:e.requestId},this.#i,o);this.batcher.enqueue(u),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let t=await j.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}});t.ok||await se({level:"error",messages:[`Failed to send logs to DataDog: ${t.status} - ${t.statusText}`]},t)}catch{await se({level:"error",messages:["Failed to connect to DataDog logging service. Check that the URL is correct."]})}},"dispatchFunction");batcher=new ie("data-dog-transport",10,this.dispatchFunction)};var sr=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===Kr){if(e.messages.length===0)return;this.#e[e.level].apply(null,[Qr(e)])}else this.#e[e.level].apply(null,[...e.messages,{logOwner:e.logOwner,logSource:e.logSource,timestamp:e.timestamp,loggingId:e.loggingId,rayId:e.rayId,requestId:e.requestId,buildId:e.buildId,vectorClock:e.vectorClock}])}};var Di=Ce("zuplo:logging"),Yr=class n{static{s(this,"LogInitializer")}systemCoreLogger;userCoreLogger;constructor({systemCoreLogger:e,userCoreLogger:t}){this.systemCoreLogger=e,this.userCoreLogger=t}static async init(e){let t=await n.setupSystemCoreLogger(y.instance,e),r=await n.setupUserCoreLogger(y.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Di("Gateway.setupSystemCoreLogger");let o=[],i=t.getService(Lr);return i?o.push(new sr(i.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new or(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new nr(e)),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new er(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Di("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=t.getService(Lr);if(a&&a.captureUserLogs===!0?r.push(new sr(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new or(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&r.push(new nr(e)),!y.instance.build.COMPATIBILITY_FLAGS.removeLegacyLogInitialization&&(o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&(g("logging.google.legacy-initialization"),r.push(new rr({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME}))),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY)){g("logging.datadog.legacy-initialization");let c=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new ir({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:c}))}return at.forEach(c=>{c instanceof Re&&r.push(c.getTransport())}),await Promise.all(r.map(async c=>{c.init&&await c.init()})),new er(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i,a){Di("Gateway.createRequestLoggers");let c=new Vr(r,o,i,a),u=new tr(e,t,this.systemCoreLogger,c);return{userRequestLogger:new tr(e,t,this.userCoreLogger,c),systemRequestLogger:u}}};var pn=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Xr=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}};var Zi=class{static{s(this,"UrlPatternRouterEntry")}constructor(e,t,r){this.fullPath=e,this.config=t,this.executableHandler=r;try{this.urlPattern=new URLPattern({pathname:this.fullPath})}catch(o){throw new ae(`Invalid path '${e}'. ${o.message}`)}}urlPattern;fullPath;config;executableHandler},eo=class{static{s(this,"UrlPatternRouter")}routeEntries=[];addRoute(e,t){if(!(e instanceof xt||e instanceof xe))throw new ae("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r;"pathPattern"in e&&e.pathPattern?r=e.pathPattern:r=e.path;try{let o=new Zi(r,e,t);Object.freeze(o.config),this.routeEntries.push(o)}catch(o){throw new Xr(`addRoute-error: Invalid path '${r}'. '${o.message}'`,{cause:o})}}lookup(e,t){if(typeof t>"u")throw new f(`Invalid request - Method was undefined. Path: '${e}'`);for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r];if(o.config.methods.includes(t)){let i=o.urlPattern.exec({pathname:e});if(i!==null)return new pn(o.config,o.executableHandler,i.pathname.groups)}}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],i=o.urlPattern.exec({pathname:e});if(i!==null){let a=new pn(o.config,o.executableHandler,i.pathname.groups);t.push(a)}}return t}};import{AsyncLocalStorage as lp}from"node:async_hooks";var to={context:new lp};var qi;function Kc(n){qi=n}s(Kc,"setGlobalZuploEventContext");function It(){if(qi===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return qi}s(It,"getGlobalZuploEventContext");function Qc({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);ac.includes(o.toLowerCase())&&!cc.includes(r.toLowerCase())&&t.delete(r)}t.delete(Qa)}else sc.forEach(r=>{t.delete(r)});return t}s(Qc,"normalizeIncomingRequestHeaders");var Et=Ce("zuplo:runtime"),Ie=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;Et("Gateway.constructor"),this.#n=this.setupRoutes(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(Et("Gateway.initialize"),!n.#e){let i=await Yr.init(r),a=await e(),c={...a,corsPolicies:Ec(a.corsPolicies)},u=new n(c,t,i,o);n.#e=u}if(!n.#e)throw new ae("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){Et("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new ae("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Br,jr,ke];setupRoutes=s(()=>{Et("Gateway.setupRoutes");let e=this.routeData,t=new eo;if(e.routes.length===0)return li(t,this),bi(t,this),yi(t,this),Tc(t,this),t;let{enabled:r,version:o}=this.runtimeSettings.developerPortal;r&&o==="legacy"&&(Uc(t,this),$c(t,this)),li(t,this),bi(t,this),yi(t,this);for(let i of at)i instanceof Ee&&i.registerRoutes(t,this);return e.routes.forEach(i=>{let a;if(typeof i.handler?.module=="object"&&(a=i.handler?.module[i.handler.export]),typeof a!="function")throw new f(`Invalid state - No handler on route for path '${i.path}'`);let c=new Te({processors:this.#r,handler:a,gateway:this}),u=new xt(i);t.addRoute(u,c.execute)}),Sc(t,this),t},"setupRoutes");errorHandler(e,t,r,o){Et("Gateway.internalErrorResponse"),t.log.error(r,o);let i={};if(y.instance.isLocalDevelopment||y.instance.isWorkingCopy)if(o instanceof k&&o.extensionMembers)i=o.extensionMembers;else if(o.cause){let a=qt(o.cause);"stack"in a&&(a.stack=Si(a.stack)),i={cause:a}}else{let a=qt(o);"stack"in a&&(a.stack=Si(a.stack)),i={cause:a}}return T.internalServerError(e,t,{detail:o.message,...i})}async handleRequest(e,t,r){let o=e.headers.get(an)??e.headers.get(Ka)??r?.parentContext?.requestId??crypto.randomUUID(),i=e.headers.get(Mt);Kc(t);let a=Qc({headers:e.headers,removeAllVendorHeadersExceptListed:y.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(an,o);let c=new Request(e,{headers:a});if(["GET","HEAD"].includes(c.method)&&c.body){let B=new Headers(c.headers);B.set(Vo,"true"),c=new Request(c,{headers:B,body:null})}c=await hc(c);let u=new URL(c.url),l=u.pathname,d=this.#n.lookup(l,c.method);if(!d)throw new ae(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p={},{userRequestLogger:m,systemRequestLogger:h}=this.#t.createRequestLoggers(o,i,t,p,c,d.routeConfiguration);cn(u)||m.debug(`Request received '${u.pathname}'`,{method:c.method,url:u.pathname,hostname:u.hostname,route:d.routeConfiguration.path});let w=new no(e.headers),b=new ue(c,{params:d.params}),P=new ro({logger:m,route:d.routeConfiguration,requestId:o,event:t,custom:p,incomingRequestProperties:w,parentContext:r?.parentContext}),N=to.context.getStore();N&&(N.context=P);let A=d.routeConfiguration.raw();dp.getActiveSpan()?.setAttributes({"http.route":P.route.path??P.route.pathPattern,"cloud.region":P.incomingRequestProperties.colo,[lt.RoutePathPattern]:P.route.pathPattern,[lt.RouteOperationId]:A.operationId,[lt.RouteTrace]:A["x-zuplo-trace"],[lt.RouteSystem]:cn(u)?!0:void 0,"net.colo":w.colo,"net.country":w.country,"net.asn":w.asn}),_e.initialize(P,b);try{if(ne.addLogger(P,h),y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!cn(u):!u.pathname.startsWith("/__zuplo")){let O=await mc(b,P);if(O instanceof Response)return O;{let F=_e.getContextExtensions(P);b=O,F.latestRequest=b}}let B=d.executableHandler;pp(B,d,c),Et("Gateway.handleRequest - call user handler");let $=await B(b,P);if(Et("Gateway.handleRequest - user handler"),!($ instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof $}`);if($.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let G;if($.headers.get(an)===null&&!$.webSocket){let O=new Headers($.headers);O.set(an,o),G=new Response($.body,{status:$.status,statusText:$.statusText,headers:O,cf:$.cf})}else G=$;return G}catch(B){return B instanceof k?(m.error(B),h.warn(B)):h.error(B),await this.errorHandler(b,P,"Error executing handler",B)}}};function pp(n,e,t){if(Et("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new f(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new f(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}s(pp,"checkHandler");import{SpanStatusCode as Yc,trace as Xc}from"@opentelemetry/api";var eu=s(async(n,e,t)=>{let r=Ie.instance.routeData.policies,o=Yn([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);let i=o[0];return await Xc.getTracer("pipeline").startActiveSpan(`policy:${i.policyName}`,async u=>{try{let l=await i.handler(e,t);if(l instanceof Request||l instanceof ue||l instanceof Response)return l instanceof Response||l instanceof ue?l:new ue(l);{let d=new f(`Invalid state - invalid handler on policy '${i.policyName}' invoked via 'invokeInboundPolicy' on route '${t.route.path}'. The result of an inbound policy must be a Response or Request.`);throw u.setStatus({code:Yc.ERROR}),u.recordException(d),d}}finally{u.end()}})},"invokeInboundPolicy"),tu=s(async(n,e,t,r)=>{let o=Ie.instance.routeData.policies,i=Xn([n],o);if(i.length===0)throw new k(`Invalid 'invokeOutboundPolicy call' - no policy '${n}' found.`);let a=i[0];return await Xc.getTracer("pipeline").startActiveSpan(`policy:${a.policyName}`,async l=>{try{let d=await a.handler(e,t,r);if(d instanceof Response)return d;{let p=new f(`Invalid state - invalid handler on policy '${a.policyName}' invoked via 'invokeOutboundPolicy' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw l.setStatus({code:Yc.ERROR}),l.recordException(p),p}}finally{l.end()}})},"invokeOutboundPolicy");function mp(n){let e={};if(!n)return e;try{let t=n.split(","),r={};return t.forEach(o=>{let[i,a]=o.split("=");i&&a&&(r[i.trim()]=a.trim())}),r.asnum&&(e[Un]=r.asnum),r.zip&&(e[Hn]=r.zip.split("+")[0]),r.dma&&(e[Fn]=r.dma),r.region_code&&(e[jn]=r.region_code),r.timezone&&(e[zn]=r.timezone),r.city&&(e[Cr]=r.city),r.continent&&(e[Or]=r.continent),r.country_code&&(e[Ar]=r.country_code),r.long&&(e[_r]=r.long),r.lat&&(e[kr]=r.lat),e}catch{return{}}}s(mp,"parseEdgeScapeHeader");function nu(n,e){let t=mp(e);for(let[r,o]of Object.entries(t))n.has(r)||n.set(r,o)}s(nu,"setZpHeadersFromAkamaiEdgeScapeHeader");var no=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e;let t=e.get(ni);if(t){let r=new Headers(e);nu(r,t),this.#e=r}}get asn(){try{let e=this.#e.get(Un);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Xo)??void 0}get city(){return this.#e.get(Wo)??this.#e.get(Cr)??void 0}get continent(){return this.#e.get(Jo)??this.#e.get(Or)??void 0}get country(){return this.#e.get(Ko)??this.#e.get(Ar)??void 0}get latitude(){return this.#e.get(Yo)??this.#e.get(kr)??void 0}get longitude(){return this.#e.get(Qo)??this.#e.get(_r)??void 0}get colo(){return this.#e.get(ei)??void 0}get postalCode(){return this.#e.get(tc)??this.#e.get(Hn)??void 0}get metroCode(){return this.#e.get(ec)??this.#e.get(Fn)??void 0}get region(){return this.#e.get(Ya)??this.#e.get(ti)??void 0}get regionCode(){return this.#e.get(Xa)??this.#e.get(jn)??void 0}get timezone(){return this.#e.get(nc)??this.#e.get(zn)??void 0}get httpProtocol(){return this.#e.get(ic)??void 0}toJSON(){return{asn:this.asn,asOrganization:this.asOrganization,city:this.city,continent:this.continent,country:this.country,latitude:this.latitude,longitude:this.longitude,colo:this.colo,postalCode:this.postalCode,metroCode:this.metroCode,region:this.region,regionCode:this.regionCode,timezone:this.timezone,httpProtocol:this.httpProtocol}}};function Tt(n){return{contextId:n.contextId,incomingRequestProperties:n.incomingRequestProperties,requestId:n.requestId,route:n.route,custom:n.custom,parentContext:n.parentContext}}s(Tt,"createRewriteContext");var Jn=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Kn=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},_e=class n{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;#t;#n;#r;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[],this.#r=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}addHandlerResponseHook(e){this.#r.push(e)}onResponseSendingFinal=s(async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)},"onResponseSendingFinal");onResponseSending=s(async(e,t,r)=>{let o=e;for(let i of this.#n)o=await i(e,t,r);return o},"onResponseSending");onHandlerResponse=s(async(e,t,r)=>{for(let o of this.#r)await o(e,t,r)},"onHandlerResponse")},ro=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:i,incomingRequestProperties:a,parentContext:c}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.parentContext=c,this.#e=o,this.invokeInboundPolicy=(u,l)=>eu(u,l,this),this.contextId=crypto.randomUUID(),this.invokeOutboundPolicy=(u,l,d)=>tu(u,l,d,this),this.invokeRoute=async(u,l)=>{let d=u;typeof u=="string"&&u.startsWith("/")&&(d=new URL(u,"http://localhost"));let p=new ue(d,l);return Ie.instance.handleRequest(p,this,{parentContext:this})},this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{_e.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{_e.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;contextId;requestId;log;route;custom;incomingRequestProperties;parentContext;invokeInboundPolicy;invokeOutboundPolicy;invokeRoute;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(e,t,r){let o=s(i=>{try{typeof t=="function"?t(i):t.handleEvent(i)}catch(a){throw this.log.error(`Error invoking event ${e}. See following logs for details.`),a}},"wrapped");super.addEventListener(e,o,r)}};var fp="Error initializing gateway. Check your configuration for errors or contact support.",gp="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",$i=class{constructor(e,t,r,o,i,a){this.routeLoader=e;this.buildEnvironment=t;this.runtimeSettings=r;this.serviceProvider=o;this.schemaValidations=i;this.runtimeInit=a}static{s(this,"Handler")}requestHandler=s(async(e,t,r)=>{y.initialize({build:this.buildEnvironment,runtime:t});try{await yc(this.runtimeInit)}catch(i){this.handleError(i,gp,e)}return dc(s(async(i,a)=>{let c;try{c=await Ie.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(l){return this.handleError(l,fp,i)}let u={context:void 0};return to.context.run(u,async()=>c.handleRequest(i,a))},"innerHandler"))(e,r)},"requestHandler");handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof f&&(t=e.message);let o={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:t,instance:r.url,trace:{timestamp:Date.now(),rayId:r.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:y.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};function hp(n){for(var e=[],t=0;t<n.length;){var r=n[t];if(r==="*"||r==="+"||r==="?"){e.push({type:"MODIFIER",index:t,value:n[t++]});continue}if(r==="\\"){e.push({type:"ESCAPED_CHAR",index:t++,value:n[t++]});continue}if(r==="{"){e.push({type:"OPEN",index:t,value:n[t++]});continue}if(r==="}"){e.push({type:"CLOSE",index:t,value:n[t++]});continue}if(r===":"){for(var o="",i=t+1;i<n.length;){var a=n.charCodeAt(i);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){o+=n[i++];continue}break}if(!o)throw new TypeError("Missing parameter name at ".concat(t));e.push({type:"NAME",index:t,value:o}),t=i;continue}if(r==="("){var c=1,u="",i=t+1;if(n[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<n.length;){if(n[i]==="\\"){u+=n[i++]+n[i++];continue}if(n[i]===")"){if(c--,c===0){i++;break}}else if(n[i]==="("&&(c++,n[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));u+=n[i++]}if(c)throw new TypeError("Unbalanced pattern at ".concat(t));if(!u)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:u}),t=i;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}s(hp,"lexer");function Hi(n,e){e===void 0&&(e={});for(var t=hp(n),r=e.prefixes,o=r===void 0?"./":r,i=e.delimiter,a=i===void 0?"/#?":i,c=[],u=0,l=0,d="",p=s(function(V){if(l<t.length&&t[l].type===V)return t[l++].value},"tryConsume"),m=s(function(V){var S=p(V);if(S!==void 0)return S;var E=t[l],U=E.type,we=E.index;throw new TypeError("Unexpected ".concat(U," at ").concat(we,", expected ").concat(V))},"mustConsume"),h=s(function(){for(var V="",S;S=p("CHAR")||p("ESCAPED_CHAR");)V+=S;return V},"consumeText"),w=s(function(V){for(var S=0,E=a;S<E.length;S++){var U=E[S];if(V.indexOf(U)>-1)return!0}return!1},"isSafe"),b=s(function(V){var S=c[c.length-1],E=V||(S&&typeof S=="string"?S:"");if(S&&!E)throw new TypeError('Must have text between two parameters, missing text after "'.concat(S.name,'"'));return!E||w(E)?"[^".concat(Ui(a),"]+?"):"(?:(?!".concat(Ui(E),")[^").concat(Ui(a),"])+?")},"safePattern");l<t.length;){var P=p("CHAR"),N=p("NAME"),A=p("PATTERN");if(N||A){var B=P||"";o.indexOf(B)===-1&&(d+=B,B=""),d&&(c.push(d),d=""),c.push({name:N||u++,prefix:B,suffix:"",pattern:A||b(B),modifier:p("MODIFIER")||""});continue}var $=P||p("ESCAPED_CHAR");if($){d+=$;continue}d&&(c.push(d),d="");var G=p("OPEN");if(G){var B=h(),O=p("NAME")||"",F=p("PATTERN")||"",Y=h();m("CLOSE"),c.push({name:O||(F?u++:""),pattern:O&&!F?b(B):F,prefix:B,suffix:Y,modifier:p("MODIFIER")||""});continue}m("END")}return c}s(Hi,"parse");function ru(n,e){return yp(Hi(n,e),e)}s(ru,"compile");function yp(n,e){e===void 0&&(e={});var t=bp(e),r=e.encode,o=r===void 0?function(u){return u}:r,i=e.validate,a=i===void 0?!0:i,c=n.map(function(u){if(typeof u=="object")return new RegExp("^(?:".concat(u.pattern,")$"),t)});return function(u){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var m=u?u[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",w=p.modifier==="*"||p.modifier==="+";if(Array.isArray(m)){if(!w)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(m.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var b=0;b<m.length;b++){var P=o(m[b],p);if(a&&!c[d].test(P))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix}continue}if(typeof m=="string"||typeof m=="number"){var P=o(String(m),p);if(a&&!c[d].test(P))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(P,'"'));l+=p.prefix+P+p.suffix;continue}if(!h){var N=w?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(N))}}return l}}s(yp,"tokensToFunction");function Ui(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(Ui,"escapeString");function bp(n){return n&&n.sensitive?"":"i"}s(bp,"flags");var wp=Ce("zuplo:runtime"),ji=new TextEncoder,ou={appstream2:"appstream",cloudhsmv2:"cloudhsm",email:"ses",marketplace:"aws-marketplace",mobile:"AWSMobileHubService",pinpoint:"mobiletargeting",queue:"sqs","git-codecommit":"codecommit","mturk-requester-sandbox":"mturk-requester","personalize-runtime":"personalize"},Rp=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],mn=class{static{s(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:e,secretAccessKey:t,sessionToken:r,service:o,region:i,cache:a,retries:c,initRetryMs:u}){if(e==null)throw new TypeError("accessKeyId is a required option");if(t==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=e,this.secretAccessKey=t,this.sessionToken=r,this.service=o,this.region=i,this.cache=a||new Map,this.retries=c??0,this.initRetryMs=u||50}async sign(e,t){let r=new zi(Object.assign({url:e},t,this,t&&t.aws)),o=Object.assign({},t,await r.sign());return delete o.aws,{url:o.url.toString(),request:o}}async fetch(e,t){wp("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,t),a=j.fetch(o,i);if(r===this.retries)return a;let c=await a;if(c.status<500&&c.status!==429)return c;await new Promise(u=>setTimeout(u,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new f("An unknown error occurred, ensure retries is not negative")}},zi=class{static{s(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:e,url:t,headers:r,body:o,accessKeyId:i,secretAccessKey:a,sessionToken:c,service:u,region:l,cache:d,datetime:p,signQuery:m,appendSessionToken:h,allHeaders:w,singleEncode:b}){if(t==null)throw new TypeError("url is a required option");if(i==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=e||(o?"POST":"GET"),this.url=new URL(t),this.headers=new Headers(r||{}),this.body=o,this.accessKeyId=i,this.secretAccessKey=a,this.sessionToken=c;let P,N;(!u||!l)&&([P,N]=vp(this.url,this.headers)),this.service=u||P||"",this.region=l||N||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=m,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let A=this.signQuery?this.url.searchParams:this.headers;if(this.service==="s3"&&!this.headers.has("X-Amz-Content-Sha256")&&this.headers.set("X-Amz-Content-Sha256","UNSIGNED-PAYLOAD"),A.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&A.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter($=>w||!Rp.includes($)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map($=>$+":"+($==="host"?this.url.host:(this.headers.get($)||"").replace(/\s+/g," "))).join(`
|
|
66
66
|
`),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!A.has("X-Amz-Expires")&&A.set("X-Amz-Expires","86400"),A.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),A.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),A.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,"/");b||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=su(this.encodedPath);let B=new Set;this.encodedSearch=[...this.url.searchParams].filter(([$])=>{if(!$)return!1;if(this.service==="s3"){if(B.has($))return!1;B.add($)}return!0}).map($=>$.map(G=>su(encodeURIComponent(G)))).sort(([$,G],[O,F])=>$<O?-1:$>O?1:G<F?-1:G>F?1:0).map($=>$.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),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await ar("AWS4"+this.secretAccessKey,e),i=await ar(o,this.region),a=await ar(i,this.service);r=await ar(a,"aws4_request"),this.cache.set(t,r)}return Fi(await ar(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Fi(await iu(await this.canonicalString()))].join(`
|
|
67
67
|
`)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
|
|
68
68
|
`,this.signedHeaders,await this.hexBodyHash()].join(`
|
|
69
|
-
`)}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 k("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Fi(await iu(this.body||""))}return e}};async function ar(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?ji.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,ji.encode(e))}s(ar,"hmac");async function iu(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?ji.encode(n):n)}s(iu,"hash");function Fi(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Fi,"buf2hex");function su(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(su,"encodeRfc3986");function vp(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,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",i="s3";else if(i==="iot")t.startsWith("iot.")?i="execute-api":t.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let c=(e.get("X-Amz-Target")||"").split(".")[0];c==="AnyScaleFrontendService"?i="application-autoscaling":c==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in ou?[ou[i],a]:[i,a]}s(vp,"guessServiceRegion");function xp(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}s(xp,"b64ToUint6");function au(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,c,u=0,l=0;for(let d=0;d<r;d++)if(c=d&3,u|=xp(t.charCodeAt(d))<<6*(3-c),c===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=u>>>(16>>>a&24)&255,a++,l++;u=0}return i}s(au,"base64Decode");function oo(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(oo,"uint6ToB64");function cu(n){let e=2,t="",r=n.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=n[i]<<(16>>>e&24),(e===2||n.length-i===1)&&(t+=String.fromCodePoint(oo(o>>>18&63),oo(o>>>12&63),oo(o>>>6&63),oo(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(cu,"base64Encode");function fn(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(fn,"numberToString");function Pp(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=fn(Math.floor(t/60)),i=fn(t%60);return`${r}${o}${i}`}s(Pp,"getCLFOffset");function Bi(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=fn(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),i=fn(n.getHours()),a=fn(n.getMinutes()),c=fn(n.getSeconds()),u=Pp(n);return`${t}/${r}/${o}:${i}:${a}:${c} ${u}`}s(Bi,"toCLFDate");var uu=Ce("zuplo:runtime"),Ip="X-Amzn-Trace-Id",Ep="x-amzn-errortype",lu=[],Tp=s(async(n,e,t)=>{let r=t;for await(let o of lu)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Ue=class extends k{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Ip)??void 0,this.errorType=t.get(Ep)??void 0}},Sp={addSendingAwsLambdaEventHook:s(n=>{lu.push(n)},"addSendingAwsLambdaEventHook")};async function Cp(n,e){g("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:c=!1,binaryMediaTypes:u}=e.route.handler.options;if(!t)throw new f("awsAccessKeyId is not set in the handler options");if(!r)throw new f("secretAccessKey is not set in the handler options");if(!o)throw new f("region is not set in the handler options");if(!i)throw new f("functionName is not set in the handler options");let l=new mn({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(uu(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,m]=await kp(n,{binaryMediaTypes:u}),{options:h}=e.route.handler,x;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?x=_p(n,e):x=await Ap(n,e,{useAwsResourcePathStyle:c}),uu("Calling onSendingAwsLambdaEvent hook");let b=await Tp(n,e,x);b.body=p,b.isBase64Encoded=m;let P=await l.fetch(d,{body:JSON.stringify(b)});try{return Op(P)}catch(N){if(N instanceof Ue){let A=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&N.traceId?{AMZN_TRACE_ID_HEADER:N.traceId}:void 0;return T.internalServerError(n,e,void 0,A)}throw N}}s(Cp,"awsLambdaHandler");async function Op(n){let e;try{e=await n.json()}catch{throw new Ue("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new Ue(e.message,n.headers):new Ue(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Ue(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Ue(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,i]of Object.entries(e.headers))t.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Ue(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new Ue(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new Ue("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Ue("Response was set to base64 encoded but body was not a string",n.headers);r=au(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new Ue(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}s(Op,"getResponse");async function Ap(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=n.query,a={};for(let[l,d]of Object.entries(i))a[l]||(a[l]=[]),a[l].push(d);let c=new URL(n.url);return{version:"1.0",resource:c.pathname,path:c.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:c.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:c.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Bi(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Np(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(Ap,"buildEventVersion1");function _p(n,e){let t={};n.headers.forEach((i,a)=>{t[a]=i});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.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:r.hostname,domainPrefix:null,http:{method:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Bi(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(_p,"buildEventVersion2");async function kp(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&Lp(e,o)){let i=await n.arrayBuffer();t=cu(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(kp,"getBodyResult");function Lp(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(Lp,"matchesContentType");function Np(n,e=!1){if(!e)return n;let t=Hi(n),r=ru(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(Np,"getResourcePath");var Mp=[502,503,504];async function gn(n,e){if(Mp.includes(n.status)){let t=ne.getLogger(e),o=await n.clone().text(),i={};for(let[a,c]of n.headers)i[a]=c;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:i})}}s(gn,"logBadGatewayResponses");var Gi;function St(n){if(Gi===void 0){let t=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Gi=t}return n.log[Gi]}s(St,"getHandlerUserLogFunction");async function Dp(n,e){g("handler.open-api");let t=y.instance.build.BUILD_ID,{buildAssetsUrl:r}=y.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new f("Open API Spec Handler must have 'openApiFilePath' specified");let a=Zp(i);if(!a.isValid)throw new f(a.error);let c=`${r}/${t}${i.substring(1)}`,u=await j.fetch(c,{method:n.method,body:n.body,headers:n.headers});if(u.status!==200)return T.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(u.body,{headers:{"content-type":"application/json","content-encoding":u.headers.get("content-encoding")||"",vary:"Accept-Encoding"},status:u.status,statusText:u.statusText});return gn(l,e),l}s(Dp,"openApiSpecHandler");var Zp=s(n=>n.startsWith("./")?n.startsWith("./config")?n.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 qp(n,e){g("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new f("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}s(qp,"redirectHandler");async function $p(n){if(g("handler.zuplo-service-proxy"),Object.entries(n.params).length!==1)throw new f("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(n.params.path,y.instance.zuploEdgeApiUrl),t=new Headers(n.headers);return t.set("Authorization",`Bearer ${y.instance.authApiJWT}`),j.fetch(e,{method:n.method,headers:t,body:n.body})}s($p,"zuploServiceProxy");function Up(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}s(Up,"join");async function Hp(n,e){g("handler.url-forward");let t=St(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i;if(y.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?i=r.followRedirects===!0?"follow":"manual":typeof r.followRedirects<"u"&&g("handler.url-forward.follow-redirects"),!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a=Tt(e),c=new URL(n.url),u=r.__rewriteFunction(n,a),l=Up(u,c.pathname),d=o?`${l}${c.search}`:l.toString(),p=Date.now();t(`URL Forwarding to '${d}'`);let m=await fetch(d,{method:n.method,body:n.body,headers:n.headers,redirect:i}),h=Date.now()-p;return t(`URL Forward received response ${m.status} - ${m.statusText} in ${h}ms`),gn(m,e),m}s(Hp,"urlForwardHandler");var Fp=s((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,i]of r.searchParams.entries())t.searchParams.append(o,i);return t.toString()},"addQuery");async function jp(n,e){g("handler.url-rewrite");let t=St(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a=Tt(e),c=r.__rewriteFunction(n,a),u=o?Fp(c,n.url):c,l=Date.now();t(`URL Rewriting to '${u}'`);let d=await fetch(u.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),gn(d,e),d}s(jp,"urlRewriteHandler");async function zp(n,e){g("handler.websocket");let t=e.route.handler.options,r=St(e);if(!t||!t.rewritePattern)throw new f("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new f("Invalid options for this route");let i=Tt(e),a=t.__rewriteFunction(n,i),c=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let u=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(u.status!==101||!u.webSocket){let d=await u.text(),p=`WebSocket connection error - ${u.status}: ${u.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-c;return r(`WebSocket connected, received response ${u.status} - ${u.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:u.webSocket})}s(zp,"webSocketHandler");var Vi=s((n,e)=>n.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${o+1}, export name: ${r.export}`;throw new f(`${a} - Websocket policy must be a valid function (${c})`)}return i}),"getWebSocketPolicyFunctions"),du=s(async(n,e,t,r,o,i)=>{let a=n.data;if(i&&i.length>0){let c=[...i];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function pu(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),n.addEventListener("message",i=>{try{let c=s(async u=>{let l=await du(u,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(c)}catch(a){r.log.error(a)}})}s(pu,"wireUpListeners");async function Bp(n,e){g("handler.websocket-pipeline");let t=e.route.handler.options,r=St(e);if(!t||!t.rewritePattern)throw new f("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new f("Invalid options for this route");let i=Tt(e),a=t.__rewriteFunction(n,i),c=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let u=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(u.status!==101||!u.webSocket){let P=await u.text(),N=`WebSocket connection error - ${u.status}: ${u.statusText}, content: '${P}'`;throw new Error(N)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-c;r(`WebSocket connected, received response ${u.status} - ${u.statusText} in ${m}ms`);let h=u.webSocket;h.accept(),p.accept();let x=t.policies&&t.policies.inbound?Vi(t.policies.inbound,"inbound"):[],b=t.policies&&t.policies.outbound?Vi(t.policies.outbound,"outbound"):[];return pu(p,h,n,e,x),pu(h,p,n,e,b),new Response(null,{status:101,webSocket:d})}s(Bp,"webSocketPipelineHandler");var pe;(function(n){n.assertEqual=o=>o;function e(o){}s(e,"assertIs"),n.assertIs=e;function t(o){throw new Error}s(t,"assertNever"),n.assertNever=t,n.arrayToEnum=o=>{let i={};for(let a of o)i[a]=a;return i},n.getValidEnumValues=o=>{let i=n.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(let c of i)a[c]=o[c];return n.objectValues(a)},n.objectValues=o=>n.objectKeys(o).map(function(i){return o[i]}),n.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);return i},n.find=(o,i)=>{for(let a of o)if(i(a))return a},n.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}s(r,"joinValues"),n.joinValues=r,n.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(pe||(pe={}));var Ji;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Ji||(Ji={}));var z=pe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),pt=s(n=>{switch(typeof n){case"undefined":return z.undefined;case"string":return z.string;case"number":return isNaN(n)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(n)?z.array:n===null?z.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?z.promise:typeof Map<"u"&&n instanceof Map?z.map:typeof Set<"u"&&n instanceof Set?z.set:typeof Date<"u"&&n instanceof Date?z.date:z.object;default:return z.unknown}},"getParsedType"),L=pe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Gp=s(n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),He=class n extends Error{static{s(this,"ZodError")}get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},r={_errors:[]},o=s(i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(t(a));else{let c=r,u=0;for(;u<a.path.length;){let l=a.path[u];u===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(t(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}},"processError");return o(this),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,pe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let o of this.issues)o.path.length>0?(t[o.path[0]]=t[o.path[0]]||[],t[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};He.create=n=>new He(n);var bn=s((n,e)=>{let t;switch(n.code){case L.invalid_type:n.received===z.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case L.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,pe.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:t=`Unrecognized key(s) in object: ${pe.joinValues(n.keys,", ")}`;break;case L.invalid_union:t="Invalid input";break;case L.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${pe.joinValues(n.options)}`;break;case L.invalid_enum_value:t=`Invalid enum value. Expected ${pe.joinValues(n.options)}, received '${n.received}'`;break;case L.invalid_arguments:t="Invalid function arguments";break;case L.invalid_return_type:t="Invalid function return type";break;case L.invalid_date:t="Invalid date";break;case L.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:pe.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case L.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case L.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case L.custom:t="Invalid input";break;case L.invalid_intersection_types:t="Intersection results could not be merged";break;case L.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case L.not_finite:t="Number must be finite";break;default:t=e.defaultError,pe.assertNever(n)}return{message:t}},"errorMap"),hu=bn;function Vp(n){hu=n}s(Vp,"setErrorMap");function io(){return hu}s(io,"getErrorMap");var so=s(n=>{let{data:e,path:t,errorMaps:r,issueData:o}=n,i=[...t,...o.path||[]],a={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let c="",u=r.filter(l=>!!l).slice().reverse();for(let l of u)c=l(a,{data:e,defaultError:c}).message;return{...o,path:i,message:c}},"makeIssue"),Wp=[];function Z(n,e){let t=io(),r=so({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===bn?void 0:bn].filter(o=>!!o)});n.common.issues.push(r)}s(Z,"addIssueToContext");var Ae=class n{static{s(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let o of t){if(o.status==="aborted")return ee;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let o of t){let i=await o.key,a=await o.value;r.push({key:i,value:a})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let o of t){let{key:i,value:a}=o;if(i.status==="aborted"||a.status==="aborted")return ee;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[i.value]=a.value)}return{status:e.value,value:r}}},ee=Object.freeze({status:"aborted"}),yn=s(n=>({status:"dirty",value:n}),"DIRTY"),Ne=s(n=>({status:"valid",value:n}),"OK"),Ki=s(n=>n.status==="aborted","isAborted"),Qi=s(n=>n.status==="dirty","isDirty"),$t=s(n=>n.status==="valid","isValid"),lr=s(n=>typeof Promise<"u"&&n instanceof Promise,"isAsync");function ao(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}s(ao,"__classPrivateFieldGet");function yu(n,e,t,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!o:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(n,t):o?o.value=t:e.set(n,t),t}s(yu,"__classPrivateFieldSet");var J;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(J||(J={}));var cr,ur,Ve=class{static{s(this,"ParseInputLazyPath")}constructor(e,t,r,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},mu=s((n,e)=>{if($t(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new He(n.common.issues);return this._error=t,this._error}}},"handleResult");function re(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:o}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:s((a,c)=>{var u,l;let{message:d}=n;return a.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(u=d??r)!==null&&u!==void 0?u:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(l=d??t)!==null&&l!==void 0?l:c.defaultError}},"customMap"),description:o}}s(re,"processCreateParams");var oe=class{static{s(this,"ZodType")}get description(){return this._def.description}_getType(e){return pt(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ae,ctx:{common:e.parent.common,data:e.data,parsedType:pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(lr(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;let o={common:{issues:[],async:(r=t?.async)!==null&&r!==void 0?r:!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)},i=this._parseSync({data:e,path:o.path,parent:o});return mu(o,i)}"~validate"(e){var t,r;let o={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)};if(!this["~standard"].async)try{let i=this._parseSync({data:e,path:[],parent:o});return $t(i)?{value:i.value}:{issues:o.common.issues}}catch(i){!((r=(t=i?.message)===null||t===void 0?void 0:t.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),o.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:o}).then(i=>$t(i)?{value:i.value}:{issues:o.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)},o=this._parse({data:e,path:r.path,parent:r}),i=await(lr(o)?o:Promise.resolve(o));return mu(r,i)}refine(e,t){let r=s(o=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(o):t,"getIssueProperties");return this._refinement((o,i)=>{let a=e(o),c=s(()=>i.addIssue({code:L.custom,...r(o)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(e,t){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof t=="function"?t(r,o):t),!1))}_refinement(e){return new Fe({schema:this,typeName:X.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s(t=>this["~validate"](t),"validate")}}optional(){return Ge.create(this,this._def)}nullable(){return ot.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ft.create(this)}promise(){return At.create(this,this._def)}or(e){return Gt.create([this,e],this._def)}and(e){return Vt.create(this,e,this._def)}transform(e){return new Fe({...re(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Yt({...re(this._def),innerType:this,defaultValue:t,typeName:X.ZodDefault})}brand(){return new dr({typeName:X.ZodBranded,type:this,...re(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Xt({...re(this._def),innerType:this,catchValue:t,typeName:X.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return pr.create(this,e)}readonly(){return en.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Jp=/^c[^\s-]{8,}$/i,Kp=/^[0-9a-z]+$/,Qp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Yp=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Xp=/^[a-z0-9_-]{21}$/i,em=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,tm=/^[-+]?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)?)??$/,nm=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,rm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Wi,om=/^(?:(?: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])$/,im=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,sm=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,am=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cm=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,um=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,bu="((\\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])))",lm=new RegExp(`^${bu}$`);function wu(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}s(wu,"timeRegexSource");function dm(n){return new RegExp(`^${wu(n)}$`)}s(dm,"timeRegex");function Ru(n){let e=`${bu}T${wu(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}s(Ru,"datetimeRegex");function pm(n,e){return!!((e==="v4"||!e)&&om.test(n)||(e==="v6"||!e)&&sm.test(n))}s(pm,"isValidIP");function mm(n,e){if(!em.test(n))return!1;try{let[t]=n.split("."),r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||!o.typ||!o.alg||e&&o.alg!==e)}catch{return!1}}s(mm,"isValidJWT");function fm(n,e){return!!((e==="v4"||!e)&&im.test(n)||(e==="v6"||!e)&&am.test(n))}s(fm,"isValidCidr");var Ct=class n extends oe{static{s(this,"ZodString")}_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let i=this._getOrReturnCtx(e);return Z(i,{code:L.invalid_type,expected:z.string,received:i.parsedType}),ee}let r=new Ae,o;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:L.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:L.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let a=e.data.length>i.value,c=e.data.length<i.value;(a||c)&&(o=this._getOrReturnCtx(e,o),a?Z(o,{code:L.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&Z(o,{code:L.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")nm.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"email",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Wi||(Wi=new RegExp(rm,"u")),Wi.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"emoji",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Yp.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"uuid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Xp.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"nanoid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Jp.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Kp.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid2",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Qp.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ulid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),Z(o,{validation:"url",code:L.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"regex",code:L.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),Z(o,{code:L.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:L.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:L.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Ru(i).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:L.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?lm.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:L.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?dm(i).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:L.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?tm.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"duration",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?pm(e.data,i.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ip",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?mm(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"jwt",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?fm(e.data,i.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cidr",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?cm.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?um.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64url",code:L.invalid_string,message:i.message}),r.dirty()):pe.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(o=>e.test(o),{validation:t,code:L.invalid_string,...J.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...J.errToObj(e)})}url(e){return this._addCheck({kind:"url",...J.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...J.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...J.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...J.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...J.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...J.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...J.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...J.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...J.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...J.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...J.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...J.errToObj(e)})}datetime(e){var t,r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(t=e?.offset)!==null&&t!==void 0?t:!1,local:(r=e?.local)!==null&&r!==void 0?r:!1,...J.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...J.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...J.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...J.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...J.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...J.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...J.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...J.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...J.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...J.errToObj(t)})}nonempty(e){return this.min(1,J.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Ct.create=n=>{var e;return new Ct({checks:[],typeName:X.ZodString,coerce:(e=n?.coerce)!==null&&e!==void 0?e:!1,...re(n)})};function gm(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=t>r?t:r,i=parseInt(n.toFixed(o).replace(".","")),a=parseInt(e.toFixed(o).replace(".",""));return i%a/Math.pow(10,o)}s(gm,"floatSafeRemainder");var Ut=class n extends oe{static{s(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let i=this._getOrReturnCtx(e);return Z(i,{code:L.invalid_type,expected:z.number,received:i.parsedType}),ee}let r,o=new Ae;for(let i of this._def.checks)i.kind==="int"?pe.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),Z(r,{code:L.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Z(r,{code:L.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Z(r,{code:L.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?gm(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),Z(r,{code:L.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),Z(r,{code:L.not_finite,message:i.message}),o.dirty()):pe.assertNever(i);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,J.toString(t))}gt(e,t){return this.setLimit("min",e,!1,J.toString(t))}lte(e,t){return this.setLimit("max",e,!0,J.toString(t))}lt(e,t){return this.setLimit("max",e,!1,J.toString(t))}setLimit(e,t,r,o){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:J.toString(o)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:J.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:J.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:J.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:J.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:J.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&pe.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Ut.create=n=>new Ut({checks:[],typeName:X.ZodNumber,coerce:n?.coerce||!1,...re(n)});var Ht=class n extends oe{static{s(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let r,o=new Ae;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Z(r,{code:L.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Z(r,{code:L.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),Z(r,{code:L.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):pe.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return Z(t,{code:L.invalid_type,expected:z.bigint,received:t.parsedType}),ee}gte(e,t){return this.setLimit("min",e,!0,J.toString(t))}gt(e,t){return this.setLimit("min",e,!1,J.toString(t))}lte(e,t){return this.setLimit("max",e,!0,J.toString(t))}lt(e,t){return this.setLimit("max",e,!1,J.toString(t))}setLimit(e,t,r,o){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:J.toString(o)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:J.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Ht.create=n=>{var e;return new Ht({checks:[],typeName:X.ZodBigInt,coerce:(e=n?.coerce)!==null&&e!==void 0?e:!1,...re(n)})};var Ft=class extends oe{static{s(this,"ZodBoolean")}_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let r=this._getOrReturnCtx(e);return Z(r,{code:L.invalid_type,expected:z.boolean,received:r.parsedType}),ee}return Ne(e.data)}};Ft.create=n=>new Ft({typeName:X.ZodBoolean,coerce:n?.coerce||!1,...re(n)});var jt=class n extends oe{static{s(this,"ZodDate")}_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let i=this._getOrReturnCtx(e);return Z(i,{code:L.invalid_type,expected:z.date,received:i.parsedType}),ee}if(isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return Z(i,{code:L.invalid_date}),ee}let r=new Ae,o;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:L.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:L.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):pe.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:J.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:J.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};jt.create=n=>new jt({checks:[],coerce:n?.coerce||!1,typeName:X.ZodDate,...re(n)});var wn=class extends oe{static{s(this,"ZodSymbol")}_parse(e){if(this._getType(e)!==z.symbol){let r=this._getOrReturnCtx(e);return Z(r,{code:L.invalid_type,expected:z.symbol,received:r.parsedType}),ee}return Ne(e.data)}};wn.create=n=>new wn({typeName:X.ZodSymbol,...re(n)});var zt=class extends oe{static{s(this,"ZodUndefined")}_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return Z(r,{code:L.invalid_type,expected:z.undefined,received:r.parsedType}),ee}return Ne(e.data)}};zt.create=n=>new zt({typeName:X.ZodUndefined,...re(n)});var Bt=class extends oe{static{s(this,"ZodNull")}_parse(e){if(this._getType(e)!==z.null){let r=this._getOrReturnCtx(e);return Z(r,{code:L.invalid_type,expected:z.null,received:r.parsedType}),ee}return Ne(e.data)}};Bt.create=n=>new Bt({typeName:X.ZodNull,...re(n)});var Ot=class extends oe{static{s(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(e){return Ne(e.data)}};Ot.create=n=>new Ot({typeName:X.ZodAny,...re(n)});var mt=class extends oe{static{s(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ne(e.data)}};mt.create=n=>new mt({typeName:X.ZodUnknown,...re(n)});var Je=class extends oe{static{s(this,"ZodNever")}_parse(e){let t=this._getOrReturnCtx(e);return Z(t,{code:L.invalid_type,expected:z.never,received:t.parsedType}),ee}};Je.create=n=>new Je({typeName:X.ZodNever,...re(n)});var Rn=class extends oe{static{s(this,"ZodVoid")}_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return Z(r,{code:L.invalid_type,expected:z.void,received:r.parsedType}),ee}return Ne(e.data)}};Rn.create=n=>new Rn({typeName:X.ZodVoid,...re(n)});var ft=class n extends oe{static{s(this,"ZodArray")}_parse(e){let{ctx:t,status:r}=this._processInputParams(e),o=this._def;if(t.parsedType!==z.array)return Z(t,{code:L.invalid_type,expected:z.array,received:t.parsedType}),ee;if(o.exactLength!==null){let a=t.data.length>o.exactLength.value,c=t.data.length<o.exactLength.value;(a||c)&&(Z(t,{code:a?L.too_big:L.too_small,minimum:c?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&t.data.length<o.minLength.value&&(Z(t,{code:L.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&t.data.length>o.maxLength.value&&(Z(t,{code:L.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((a,c)=>o.type._parseAsync(new Ve(t,a,t.path,c)))).then(a=>Ae.mergeArray(r,a));let i=[...t.data].map((a,c)=>o.type._parseSync(new Ve(t,a,t.path,c)));return Ae.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:J.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:J.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:J.toString(t)}})}nonempty(e){return this.min(1,e)}};ft.create=(n,e)=>new ft({type:n,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...re(e)});function hn(n){if(n instanceof De){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=Ge.create(hn(r))}return new De({...n._def,shape:s(()=>e,"shape")})}else return n instanceof ft?new ft({...n._def,type:hn(n.element)}):n instanceof Ge?Ge.create(hn(n.unwrap())):n instanceof ot?ot.create(hn(n.unwrap())):n instanceof rt?rt.create(n.items.map(e=>hn(e))):n}s(hn,"deepPartialify");var De=class n extends oe{static{s(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=pe.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==z.object){let l=this._getOrReturnCtx(e);return Z(l,{code:L.invalid_type,expected:z.object,received:l.parsedType}),ee}let{status:r,ctx:o}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Je&&this._def.unknownKeys==="strip"))for(let l in o.data)a.includes(l)||c.push(l);let u=[];for(let l of a){let d=i[l],p=o.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new Ve(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Je){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of c)u.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(l==="strict")c.length>0&&(Z(o,{code:L.unrecognized_keys,keys:c}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of c){let p=o.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new Ve(o,p,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of u){let p=await d.key,m=await d.value;l.push({key:p,value:m,alwaysSet:d.alwaysSet})}return l}).then(l=>Ae.mergeObjectSync(r,l)):Ae.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return J.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:s((t,r)=>{var o,i,a,c;let u=(a=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,t,r).message)!==null&&a!==void 0?a:r.defaultError;return t.code==="unrecognized_keys"?{message:(c=J.errToObj(e).message)!==null&&c!==void 0?c:u}:{message:u}},"errorMap")}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:s(()=>({...this._def.shape(),...e}),"shape")})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:s(()=>({...this._def.shape(),...e._def.shape()}),"shape"),typeName:X.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};return pe.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new n({...this._def,shape:s(()=>t,"shape")})}omit(e){let t={};return pe.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new n({...this._def,shape:s(()=>t,"shape")})}deepPartial(){return hn(this)}partial(e){let t={};return pe.objectKeys(this.shape).forEach(r=>{let o=this.shape[r];e&&!e[r]?t[r]=o:t[r]=o.optional()}),new n({...this._def,shape:s(()=>t,"shape")})}required(e){let t={};return pe.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ge;)i=i._def.innerType;t[r]=i}}),new n({...this._def,shape:s(()=>t,"shape")})}keyof(){return vu(pe.objectKeys(this.shape))}};De.create=(n,e)=>new De({shape:s(()=>n,"shape"),unknownKeys:"strip",catchall:Je.create(),typeName:X.ZodObject,...re(e)});De.strictCreate=(n,e)=>new De({shape:s(()=>n,"shape"),unknownKeys:"strict",catchall:Je.create(),typeName:X.ZodObject,...re(e)});De.lazycreate=(n,e)=>new De({shape:n,unknownKeys:"strip",catchall:Je.create(),typeName:X.ZodObject,...re(e)});var Gt=class extends oe{static{s(this,"ZodUnion")}_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function o(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;let a=i.map(c=>new He(c.ctx.common.issues));return Z(t,{code:L.invalid_union,unionErrors:a}),ee}if(s(o,"handleResults"),t.common.async)return Promise.all(r.map(async i=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(o);{let i,a=[];for(let u of r){let l={...t,common:{...t.common,issues:[]},parent:null},d=u._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let c=a.map(u=>new He(u));return Z(t,{code:L.invalid_union,unionErrors:c}),ee}}get options(){return this._def.options}};Gt.create=(n,e)=>new Gt({options:n,typeName:X.ZodUnion,...re(e)});var dt=s(n=>n instanceof Wt?dt(n.schema):n instanceof Fe?dt(n.innerType()):n instanceof Jt?[n.value]:n instanceof Kt?n.options:n instanceof Qt?pe.objectValues(n.enum):n instanceof Yt?dt(n._def.innerType):n instanceof zt?[void 0]:n instanceof Bt?[null]:n instanceof Ge?[void 0,...dt(n.unwrap())]:n instanceof ot?[null,...dt(n.unwrap())]:n instanceof dr||n instanceof en?dt(n.unwrap()):n instanceof Xt?dt(n._def.innerType):[],"getDiscriminator"),co=class n extends oe{static{s(this,"ZodDiscriminatedUnion")}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.object)return Z(t,{code:L.invalid_type,expected:z.object,received:t.parsedType}),ee;let r=this.discriminator,o=t.data[r],i=this.optionsMap.get(o);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(Z(t,{code:L.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),ee)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let o=new Map;for(let i of t){let a=dt(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of a){if(o.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);o.set(c,i)}}return new n({typeName:X.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...re(r)})}};function Yi(n,e){let t=pt(n),r=pt(e);if(n===e)return{valid:!0,data:n};if(t===z.object&&r===z.object){let o=pe.objectKeys(e),i=pe.objectKeys(n).filter(c=>o.indexOf(c)!==-1),a={...n,...e};for(let c of i){let u=Yi(n[c],e[c]);if(!u.valid)return{valid:!1};a[c]=u.data}return{valid:!0,data:a}}else if(t===z.array&&r===z.array){if(n.length!==e.length)return{valid:!1};let o=[];for(let i=0;i<n.length;i++){let a=n[i],c=e[i],u=Yi(a,c);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return t===z.date&&r===z.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}s(Yi,"mergeValues");var Vt=class extends oe{static{s(this,"ZodIntersection")}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),o=s((i,a)=>{if(Ki(i)||Ki(a))return ee;let c=Yi(i.value,a.value);return c.valid?((Qi(i)||Qi(a))&&t.dirty(),{status:t.value,value:c.data}):(Z(r,{code:L.invalid_intersection_types}),ee)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>o(i,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Vt.create=(n,e,t)=>new Vt({left:n,right:e,typeName:X.ZodIntersection,...re(t)});var rt=class n extends oe{static{s(this,"ZodTuple")}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.array)return Z(r,{code:L.invalid_type,expected:z.array,received:r.parsedType}),ee;if(r.data.length<this._def.items.length)return Z(r,{code:L.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ee;!this._def.rest&&r.data.length>this._def.items.length&&(Z(r,{code:L.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((a,c)=>{let u=this._def.items[c]||this._def.rest;return u?u._parse(new Ve(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>Ae.mergeArray(t,a)):Ae.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};rt.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new rt({items:n,typeName:X.ZodTuple,rest:null,...re(e)})};var uo=class n extends oe{static{s(this,"ZodRecord")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return Z(r,{code:L.invalid_type,expected:z.object,received:r.parsedType}),ee;let o=[],i=this._def.keyType,a=this._def.valueType;for(let c in r.data)o.push({key:i._parse(new Ve(r,c,r.path,c)),value:a._parse(new Ve(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?Ae.mergeObjectAsync(t,o):Ae.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof oe?new n({keyType:e,valueType:t,typeName:X.ZodRecord,...re(r)}):new n({keyType:Ct.create(),valueType:e,typeName:X.ZodRecord,...re(t)})}},vn=class extends oe{static{s(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.map)return Z(r,{code:L.invalid_type,expected:z.map,received:r.parsedType}),ee;let o=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,u],l)=>({key:o._parse(new Ve(r,c,r.path,[l,"key"])),value:i._parse(new Ve(r,u,r.path,[l,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let u of a){let l=await u.key,d=await u.value;if(l.status==="aborted"||d.status==="aborted")return ee;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(l.value,d.value)}return{status:t.value,value:c}})}else{let c=new Map;for(let u of a){let l=u.key,d=u.value;if(l.status==="aborted"||d.status==="aborted")return ee;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(l.value,d.value)}return{status:t.value,value:c}}}};vn.create=(n,e,t)=>new vn({valueType:e,keyType:n,typeName:X.ZodMap,...re(t)});var xn=class n extends oe{static{s(this,"ZodSet")}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.set)return Z(r,{code:L.invalid_type,expected:z.set,received:r.parsedType}),ee;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(Z(r,{code:L.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(Z(r,{code:L.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty());let i=this._def.valueType;function a(u){let l=new Set;for(let d of u){if(d.status==="aborted")return ee;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}s(a,"finalizeSet");let c=[...r.data.values()].map((u,l)=>i._parse(new Ve(r,u,r.path,l)));return r.common.async?Promise.all(c).then(u=>a(u)):a(c)}min(e,t){return new n({...this._def,minSize:{value:e,message:J.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:J.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};xn.create=(n,e)=>new xn({valueType:n,minSize:null,maxSize:null,typeName:X.ZodSet,...re(e)});var lo=class n extends oe{static{s(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.function)return Z(t,{code:L.invalid_type,expected:z.function,received:t.parsedType}),ee;function r(c,u){return so({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,io(),bn].filter(l=>!!l),issueData:{code:L.invalid_arguments,argumentsError:u}})}s(r,"makeArgsIssue");function o(c,u){return so({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,io(),bn].filter(l=>!!l),issueData:{code:L.invalid_return_type,returnTypeError:u}})}s(o,"makeReturnsIssue");let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof At){let c=this;return Ne(async function(...u){let l=new He([]),d=await c._def.args.parseAsync(u,i).catch(h=>{throw l.addIssue(r(u,h)),l}),p=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(p,i).catch(h=>{throw l.addIssue(o(p,h)),l})})}else{let c=this;return Ne(function(...u){let l=c._def.args.safeParse(u,i);if(!l.success)throw new He([r(u,l.error)]);let d=Reflect.apply(a,this,l.data),p=c._def.returns.safeParse(d,i);if(!p.success)throw new He([o(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:rt.create(e).rest(mt.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||rt.create([]).rest(mt.create()),returns:t||mt.create(),typeName:X.ZodFunction,...re(r)})}},Wt=class extends oe{static{s(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Wt.create=(n,e)=>new Wt({getter:n,typeName:X.ZodLazy,...re(e)});var Jt=class extends oe{static{s(this,"ZodLiteral")}_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return Z(t,{received:t.data,code:L.invalid_literal,expected:this._def.value}),ee}return{status:"valid",value:e.data}}get value(){return this._def.value}};Jt.create=(n,e)=>new Jt({value:n,typeName:X.ZodLiteral,...re(e)});function vu(n,e){return new Kt({values:n,typeName:X.ZodEnum,...re(e)})}s(vu,"createZodEnum");var Kt=class n extends oe{static{s(this,"ZodEnum")}constructor(){super(...arguments),cr.set(this,void 0)}_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return Z(t,{expected:pe.joinValues(r),received:t.parsedType,code:L.invalid_type}),ee}if(ao(this,cr,"f")||yu(this,cr,new Set(this._def.values),"f"),!ao(this,cr,"f").has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return Z(t,{received:t.data,code:L.invalid_enum_value,options:r}),ee}return Ne(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};cr=new WeakMap;Kt.create=vu;var Qt=class extends oe{static{s(this,"ZodNativeEnum")}constructor(){super(...arguments),ur.set(this,void 0)}_parse(e){let t=pe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==z.string&&r.parsedType!==z.number){let o=pe.objectValues(t);return Z(r,{expected:pe.joinValues(o),received:r.parsedType,code:L.invalid_type}),ee}if(ao(this,ur,"f")||yu(this,ur,new Set(pe.getValidEnumValues(this._def.values)),"f"),!ao(this,ur,"f").has(e.data)){let o=pe.objectValues(t);return Z(r,{received:r.data,code:L.invalid_enum_value,options:o}),ee}return Ne(e.data)}get enum(){return this._def.values}};ur=new WeakMap;Qt.create=(n,e)=>new Qt({values:n,typeName:X.ZodNativeEnum,...re(e)});var At=class extends oe{static{s(this,"ZodPromise")}unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.promise&&t.common.async===!1)return Z(t,{code:L.invalid_type,expected:z.promise,received:t.parsedType}),ee;let r=t.parsedType===z.promise?t.data:Promise.resolve(t.data);return Ne(r.then(o=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}};At.create=(n,e)=>new At({type:n,typeName:X.ZodPromise,...re(e)});var Fe=class extends oe{static{s(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),o=this._def.effect||null,i={addIssue:s(a=>{Z(r,a),a.fatal?t.abort():t.dirty()},"addIssue"),get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let a=o.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(t.value==="aborted")return ee;let u=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return u.status==="aborted"?ee:u.status==="dirty"||t.value==="dirty"?yn(u.value):u});{if(t.value==="aborted")return ee;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?ee:c.status==="dirty"||t.value==="dirty"?yn(c.value):c}}if(o.type==="refinement"){let a=s(c=>{let u=o.refinement(c,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?ee:(c.status==="dirty"&&t.dirty(),a(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?ee:(c.status==="dirty"&&t.dirty(),a(c.value).then(()=>({status:t.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!$t(a))return a;let c=o.transform(a.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>$t(a)?Promise.resolve(o.transform(a.value,i)).then(c=>({status:t.value,value:c})):a);pe.assertNever(o)}};Fe.create=(n,e,t)=>new Fe({schema:n,typeName:X.ZodEffects,effect:e,...re(t)});Fe.createWithPreprocess=(n,e,t)=>new Fe({schema:e,effect:{type:"preprocess",transform:n},typeName:X.ZodEffects,...re(t)});var Ge=class extends oe{static{s(this,"ZodOptional")}_parse(e){return this._getType(e)===z.undefined?Ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ge.create=(n,e)=>new Ge({innerType:n,typeName:X.ZodOptional,...re(e)});var ot=class extends oe{static{s(this,"ZodNullable")}_parse(e){return this._getType(e)===z.null?Ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ot.create=(n,e)=>new ot({innerType:n,typeName:X.ZodNullable,...re(e)});var Yt=class extends oe{static{s(this,"ZodDefault")}_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===z.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Yt.create=(n,e)=>new Yt({innerType:n,typeName:X.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...re(e)});var Xt=class extends oe{static{s(this,"ZodCatch")}_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return lr(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new He(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new He(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Xt.create=(n,e)=>new Xt({innerType:n,typeName:X.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...re(e)});var Pn=class extends oe{static{s(this,"ZodNaN")}_parse(e){if(this._getType(e)!==z.nan){let r=this._getOrReturnCtx(e);return Z(r,{code:L.invalid_type,expected:z.nan,received:r.parsedType}),ee}return{status:"valid",value:e.data}}};Pn.create=n=>new Pn({typeName:X.ZodNaN,...re(n)});var hm=Symbol("zod_brand"),dr=class extends oe{static{s(this,"ZodBranded")}_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},pr=class n extends oe{static{s(this,"ZodPipeline")}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return s(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?ee:i.status==="dirty"?(t.dirty(),yn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})},"handleAsync")();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?ee:o.status==="dirty"?(t.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:X.ZodPipeline})}},en=class extends oe{static{s(this,"ZodReadonly")}_parse(e){let t=this._def.innerType._parse(e),r=s(o=>($t(o)&&(o.value=Object.freeze(o.value)),o),"freeze");return lr(t)?t.then(o=>r(o)):r(t)}unwrap(){return this._def.innerType}};en.create=(n,e)=>new en({innerType:n,typeName:X.ZodReadonly,...re(e)});function fu(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}s(fu,"cleanParams");function xu(n,e={},t){return n?Ot.create().superRefine((r,o)=>{var i,a;let c=n(r);if(c instanceof Promise)return c.then(u=>{var l,d;if(!u){let p=fu(e,r),m=(d=(l=p.fatal)!==null&&l!==void 0?l:t)!==null&&d!==void 0?d:!0;o.addIssue({code:"custom",...p,fatal:m})}});if(!c){let u=fu(e,r),l=(a=(i=u.fatal)!==null&&i!==void 0?i:t)!==null&&a!==void 0?a:!0;o.addIssue({code:"custom",...u,fatal:l})}}):Ot.create()}s(xu,"custom");var ym={object:De.lazycreate},X;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(X||(X={}));var bm=s((n,e={message:`Input not instance of ${n.name}`})=>xu(t=>t instanceof n,e),"instanceOfType"),Pu=Ct.create,Iu=Ut.create,wm=Pn.create,Rm=Ht.create,Eu=Ft.create,vm=jt.create,xm=wn.create,Pm=zt.create,Im=Bt.create,Em=Ot.create,Tm=mt.create,Sm=Je.create,Cm=Rn.create,Om=ft.create,Am=De.create,_m=De.strictCreate,km=Gt.create,Lm=co.create,Nm=Vt.create,Mm=rt.create,Dm=uo.create,Zm=vn.create,qm=xn.create,$m=lo.create,Um=Wt.create,Hm=Jt.create,Fm=Kt.create,jm=Qt.create,zm=At.create,gu=Fe.create,Bm=Ge.create,Gm=ot.create,Vm=Fe.createWithPreprocess,Wm=pr.create,Jm=s(()=>Pu().optional(),"ostring"),Km=s(()=>Iu().optional(),"onumber"),Qm=s(()=>Eu().optional(),"oboolean"),Ym={string:s(n=>Ct.create({...n,coerce:!0}),"string"),number:s(n=>Ut.create({...n,coerce:!0}),"number"),boolean:s(n=>Ft.create({...n,coerce:!0}),"boolean"),bigint:s(n=>Ht.create({...n,coerce:!0}),"bigint"),date:s(n=>jt.create({...n,coerce:!0}),"date")},Xm=ee,v=Object.freeze({__proto__:null,defaultErrorMap:bn,setErrorMap:Vp,getErrorMap:io,makeIssue:so,EMPTY_PATH:Wp,addIssueToContext:Z,ParseStatus:Ae,INVALID:ee,DIRTY:yn,OK:Ne,isAborted:Ki,isDirty:Qi,isValid:$t,isAsync:lr,get util(){return pe},get objectUtil(){return Ji},ZodParsedType:z,getParsedType:pt,ZodType:oe,datetimeRegex:Ru,ZodString:Ct,ZodNumber:Ut,ZodBigInt:Ht,ZodBoolean:Ft,ZodDate:jt,ZodSymbol:wn,ZodUndefined:zt,ZodNull:Bt,ZodAny:Ot,ZodUnknown:mt,ZodNever:Je,ZodVoid:Rn,ZodArray:ft,ZodObject:De,ZodUnion:Gt,ZodDiscriminatedUnion:co,ZodIntersection:Vt,ZodTuple:rt,ZodRecord:uo,ZodMap:vn,ZodSet:xn,ZodFunction:lo,ZodLazy:Wt,ZodLiteral:Jt,ZodEnum:Kt,ZodNativeEnum:Qt,ZodPromise:At,ZodEffects:Fe,ZodTransformer:Fe,ZodOptional:Ge,ZodNullable:ot,ZodDefault:Yt,ZodCatch:Xt,ZodNaN:Pn,BRAND:hm,ZodBranded:dr,ZodPipeline:pr,ZodReadonly:en,custom:xu,Schema:oe,ZodSchema:oe,late:ym,get ZodFirstPartyTypeKind(){return X},coerce:Ym,any:Em,array:Om,bigint:Rm,boolean:Eu,date:vm,discriminatedUnion:Lm,effect:gu,enum:Fm,function:$m,instanceof:bm,intersection:Nm,lazy:Um,literal:Hm,map:Zm,nan:wm,nativeEnum:jm,never:Sm,null:Im,nullable:Gm,number:Iu,object:Am,oboolean:Qm,onumber:Km,optional:Bm,ostring:Jm,pipeline:Wm,preprocess:Vm,promise:zm,record:Dm,set:qm,strictObject:_m,string:Pu,symbol:xm,transformer:gu,tuple:Mm,undefined:Pm,union:km,unknown:Tm,void:Cm,NEVER:Xm,ZodIssueCode:L,quotelessJson:Gp,ZodError:He});var _t="2.0",Tu;(function(n){n[n.ConnectionClosed=-32e3]="ConnectionClosed",n[n.RequestTimeout=-32001]="RequestTimeout",n[n.ParseError=-32700]="ParseError",n[n.InvalidRequest=-32600]="InvalidRequest",n[n.MethodNotFound=-32601]="MethodNotFound",n[n.InvalidParams=-32602]="InvalidParams",n[n.InternalError=-32603]="InternalError"})(Tu||(Tu={}));var In=v.union([v.string(),v.number().int()]);var ef=v.object({jsonrpc:v.literal(_t),id:In,error:v.object({code:v.number().int(),message:v.string(),data:v.optional(v.unknown())})}).strict();var Xi=v.object({_meta:v.optional(v.object({}).passthrough())}).passthrough(),En=v.object({method:v.string(),params:v.optional(Xi)}),Su=v.object({jsonrpc:v.literal(_t)}).merge(En).strict();var tf=v.union([v.string(),v.number().int()]),nf=v.object({progressToken:v.optional(tf)}).passthrough(),gt=v.object({_meta:v.optional(nf)}).passthrough(),ht=v.object({method:v.string(),params:v.optional(gt)}),Cu=v.object({jsonrpc:v.literal(_t),id:In}).merge(ht).strict();var yt=v.object({_meta:v.optional(v.object({}).passthrough())}).passthrough(),ME=yt.strict(),Ou=v.object({jsonrpc:v.literal(_t),id:In,result:yt}).strict();var mr=s(n=>Cu.safeParse(n).success,"isJSONRPCRequest"),Au=s(n=>Su.safeParse(n).success,"isJSONRPCNotification"),po=s(n=>Ou.safeParse(n).success,"isJSONRPCResponse");var es=v.string();var fr=ht.extend({params:gt.extend({cursor:v.optional(es)}).optional()}),gr=yt.extend({nextCursor:v.optional(es)});var _u=v.object({uri:v.string(),mimeType:v.optional(v.string())}).passthrough(),ts=_u.extend({text:v.string()}),ns=_u.extend({blob:v.string().base64()}),rf=v.object({uri:v.string(),name:v.string(),description:v.optional(v.string()),mimeType:v.optional(v.string())}).passthrough(),of=v.object({uriTemplate:v.string(),name:v.string(),description:v.optional(v.string()),mimeType:v.optional(v.string())}).passthrough(),tT=fr.extend({method:v.literal("resources/list")}),nT=gr.extend({resources:v.array(rf)}),rT=fr.extend({method:v.literal("resources/templates/list")}),oT=gr.extend({resourceTemplates:v.array(of)}),iT=ht.extend({method:v.literal("resources/read"),params:gt.extend({uri:v.string()})}),sT=yt.extend({contents:v.array(v.union([ts,ns]))}),aT=En.extend({method:v.literal("notifications/resources/list_changed")}),cT=ht.extend({method:v.literal("resources/subscribe"),params:gt.extend({uri:v.string()})}),uT=ht.extend({method:v.literal("resources/unsubscribe"),params:gt.extend({uri:v.string()})}),lT=En.extend({method:v.literal("notifications/resources/updated"),params:Xi.extend({uri:v.string()})});var ku=v.object({type:v.literal("text"),text:v.string()}).passthrough(),Lu=v.object({type:v.literal("image"),data:v.string().base64(),mimeType:v.string()}).passthrough(),Nu=v.object({type:v.literal("audio"),data:v.string().base64(),mimeType:v.string()}).passthrough(),Mu=v.object({type:v.literal("resource"),resource:v.union([ts,ns])}).passthrough();var sf=v.object({title:v.optional(v.string()),readOnlyHint:v.optional(v.boolean()),destructiveHint:v.optional(v.boolean()),idempotentHint:v.optional(v.boolean()),openWorldHint:v.optional(v.boolean())}).passthrough(),af=v.object({name:v.string(),description:v.optional(v.string()),inputSchema:v.object({type:v.literal("object"),properties:v.optional(v.object({}).passthrough())}).passthrough(),annotations:v.optional(sf)}).passthrough(),vT=fr.extend({method:v.literal("tools/list")}),xT=gr.extend({tools:v.array(af)}),cf=yt.extend({content:v.array(v.union([ku,Lu,Nu,Mu])),isError:v.boolean().default(!1).optional()}),PT=cf.or(yt.extend({toolResult:v.unknown()})),Du=ht.extend({method:v.literal("tools/call"),params:gt.extend({name:v.string(),arguments:v.optional(v.record(v.unknown()))})}),IT=En.extend({method:v.literal("notifications/tools/list_changed")});var Zu="2025-03-26";var mo=class{static{s(this,"MCPServer")}capabilities;tools=new Map;name;version;instructions;constructor(e){this.name=e.name||"MCP Server",this.version=e.version||"1.0.0",this.instructions=e.instructions||void 0,this.capabilities={tools:{supported:!0,available:[]},...e.capabilities}}withTransport(e){e.onMessage(async t=>{try{if(mr(t)){let r=await this.handleRequest(t);if(r)return await e.send(r),r}else{if(Au(t))return await this.handleNotification(t),null;if(po(t))return console.log("Received response:",t),null}}catch(r){if(console.error("Error processing message:",r),mr(t)){let o={jsonrpc:"2.0",id:t.id,error:{code:-32603,message:r instanceof Error?r.message:"Internal error"}};return await e.send(o),o}}return null})}getTool(e){throw new Error("Method not implemented.")}getTools(){throw new Error("Method not implemented.")}getCapabilities(){return{...this.capabilities}}addTool(e){let{name:t,validator:r,handler:o,description:i=`Execute the ${t} tool`}=e,c={tool:{name:t,description:i,inputSchema:r.jsonSchema},validator:r,handler:o};this.tools.set(t,c),this.updateAvailableTools()}removeTool(e){let t=this.tools.delete(e);return t&&this.updateAvailableTools(),t}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(t){return console.error("Error handling request:",t),{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:t instanceof Error?t.message:"Internal error"}}}}async handleNotification(e){console.log("received notification",e.method)}handlePing(e){return{jsonrpc:"2.0",id:e.id,result:{}}}handleInitialize(e){let t={protocolVersion:Zu,capabilities:this.getCapabilities(),serverInfo:{name:this.name,version:this.version},...this.instructions?{instructions:this.instructions}:{}};return{jsonrpc:"2.0",id:e.id,result:t}}async handleToolListRequest(e){let r={tools:Array.from(this.tools.entries()).map(([o,i])=>i.tool)};return{jsonrpc:"2.0",id:e.id,result:r}}async handleToolCallRequest(e){let t=Du.safeParse(e);if(!t.success)return console.log("could not validate tool call with calltoolrequestschema"),{jsonrpc:"2.0",id:e.id,error:{code:-32600,message:`Invalid request ${t.error}`}};let r=t.data,o=r.params.name,i=this.tools.get(o);if(!i)return{jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Tool "${o}" not found`}};let a=r.params.arguments??{},c=i.validator.parse(a);if(!c.success)return{jsonrpc:"2.0",id:e.id,error:{code:-32602,message:"Invalid params",data:c.error}};try{let u=c.data,l=await i.handler(u);return{jsonrpc:"2.0",id:e.id,result:l}}catch(u){return console.error(`Error executing tool "${o}":`,u),{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:u instanceof Error?u.message:"Tool execution error"}}}}updateAvailableTools(){this.capabilities.tools&&(this.capabilities.tools.available=Array.from(this.tools.keys()))}};var fo=class{static{s(this,"HTTPStreamableTransport")}messageHandler=null;closeCallback=null;options;connected=!1;enableStreaming=!1;sessions=new Map;streams=new Map;constructor(e={},t=!1){this.options={timeout:30*60*1e3,enableSessions:!1,...e},t&&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(po(e)){for(let[t,r]of this.sessions.entries())for(let[o,i]of r.streams.entries())if(i.pendingRequests.has(e.id)){await this.sendToStream(i,e),i.pendingRequests.delete(e.id),i.pendingRequests.size===0&&await this.closeStream(t,o);return}}else for(let t of this.sessions.values()){let r=[...t.streams.values()][0];r&&(await this.sendToStream(r,e),mr(e)&&r.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[t,r]of e.streams.entries())try{await r.writer.close()}catch(o){console.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 t=e.method.toUpperCase();try{this.validateOrigin(e);let r=e.headers.get("Mcp-Session-Id"),o;if(r&&(o=this.sessions.get(r),!o&&t!=="DELETE"))return new Response(null,{status:404});switch(t){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(r){console.error("Error handling request:",r);let o=400,i={jsonrpc:"2.0",error:{code:-32603,message:r||"Server error"},id:null};return new Response(JSON.stringify(i),{status:o,headers:{"Content-Type":"application/json"}})}}async handlePostRequest(e,t){let r=e.headers.get("Accept")||"";if(!r.includes("application/json")&&!r.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 i=Array.isArray(o)?o:[o],a=i.some(u=>this.isRequest(u)),c=t;if(this.options.enableSessions&&!c&&i.some(u=>this.isRequest(u)&&u.method==="initialize")){let u=this.generateFallbackUUID();c=this.createSession(u)}try{if(!a){for(let m of i)await this.messageHandler?.(m);return new Response(null,{status:202,headers:c?{"Mcp-Session-Id":c.id}:void 0})}if(!this.enableStreaming){let m=[];for(let b of i)if(this.isRequest(b)){let P=await this.messageHandler?.(b);P&&m.push(P)}else await this.messageHandler?.(b);let h=m.length===1?m[0]:m,x={"Content-Type":"application/json"};return c&&(x["Mcp-Session-Id"]=c.id),new Response(JSON.stringify(h),{status:200,headers:x})}let{stream:u,streamId:l}=this.createStream(c),d=[];for(let m of i)if(this.isRequest(m)){this.streams.get(l)?.pendingRequests.add(m.id);let h=this.messageHandler?.(m);d.push(h)}else await this.messageHandler?.(m);let p={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};return c&&(p["Mcp-Session-Id"]=c.id),new Response(u.readable,{headers:p})}catch(u){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:u||"Internal error"},id:null}),{status:500,headers:{"Content-Type":"application/json"}})}}async handleGetRequest(e,t){if(!(e.headers.get("Accept")||"").includes("text/event-stream"))return new Response(null,{status:406,headers:{"Content-Type":"application/json"}});if(this.options.enableSessions&&!t)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:i}=this.createStream(t),a=e.headers.get("Last-Event-ID");a&&t&&await this.replayMessages(t,i,a);let c={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};return t&&(c["Mcp-Session-Id"]=t.id),new Response(o.readable,{headers:c})}async handleDeleteRequest(e,t){if(!t)return new Response(null,{status:400});if(this.options.enableSessions&&t){let r=this.sessions.get(t);if(r){for(let[o,i]of r.streams.entries())await this.closeStream(t,o);return this.sessions.delete(t),new Response(null,{status:204})}}return new Response(null,{status:404})}async sendToStream(e,t){try{let r=String(++e.eventCounter),o=JSON.stringify(t);e.messages.push(t),e.messages.length>100&&e.messages.shift();let i=`id: ${r}
|
|
69
|
+
`)}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 k("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Fi(await iu(this.body||""))}return e}};async function ar(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?ji.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,ji.encode(e))}s(ar,"hmac");async function iu(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?ji.encode(n):n)}s(iu,"hash");function Fi(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Fi,"buf2hex");function su(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(su,"encodeRfc3986");function vp(n,e){let{hostname:t,pathname:r}=n,o=t.replace("dualstack.","").match(/([^.]+)\.(?:([^.]*)\.)?amazonaws\.com(?:\.cn)?$/),[i,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",i="s3";else if(i==="iot")t.startsWith("iot.")?i="execute-api":t.startsWith("data.jobs.iot.")?i="iot-jobs-data":i=r==="/mqtt"?"iotdevicegateway":"iotdata";else if(i==="autoscaling"){let c=(e.get("X-Amz-Target")||"").split(".")[0];c==="AnyScaleFrontendService"?i="application-autoscaling":c==="AnyScaleScalingPlannerFrontendService"&&(i="autoscaling-plans")}else a==null&&i.startsWith("s3-")?(a=i.slice(3).replace(/^fips-|^external-1/,""),i="s3"):i.endsWith("-fips")?i=i.slice(0,-5):a&&/-\d$/.test(i)&&!/-\d$/.test(a)&&([i,a]=[a,i]);return i in ou?[ou[i],a]:[i,a]}s(vp,"guessServiceRegion");function xp(n){return n>64&&n<91?n-65:n>96&&n<123?n-71:n>47&&n<58?n+4:n===43?62:n===47?63:0}s(xp,"b64ToUint6");function au(n,e){let t=n.replace(/[^A-Za-z0-9+/]/g,""),r=t.length,o=e?Math.ceil((r*3+1>>2)/e)*e:r*3+1>>2,i=new Uint8Array(o),a,c,u=0,l=0;for(let d=0;d<r;d++)if(c=d&3,u|=xp(t.charCodeAt(d))<<6*(3-c),c===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=u>>>(16>>>a&24)&255,a++,l++;u=0}return i}s(au,"base64Decode");function oo(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(oo,"uint6ToB64");function cu(n){let e=2,t="",r=n.length,o=0;for(let i=0;i<r;i++)e=i%3,o|=n[i]<<(16>>>e&24),(e===2||n.length-i===1)&&(t+=String.fromCodePoint(oo(o>>>18&63),oo(o>>>12&63),oo(o>>>6&63),oo(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(cu,"base64Encode");function fn(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(fn,"numberToString");function Pp(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=fn(Math.floor(t/60)),i=fn(t%60);return`${r}${o}${i}`}s(Pp,"getCLFOffset");function Bi(n=new Date){if(!(n instanceof Date))throw new Error("clf-date: invalid parameter");let e=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],t=fn(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),i=fn(n.getHours()),a=fn(n.getMinutes()),c=fn(n.getSeconds()),u=Pp(n);return`${t}/${r}/${o}:${i}:${a}:${c} ${u}`}s(Bi,"toCLFDate");var uu=Ce("zuplo:runtime"),Ip="X-Amzn-Trace-Id",Ep="x-amzn-errortype",lu=[],Tp=s(async(n,e,t)=>{let r=t;for await(let o of lu)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Ue=class extends k{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(Ip)??void 0,this.errorType=t.get(Ep)??void 0}},Sp={addSendingAwsLambdaEventHook:s(n=>{lu.push(n)},"addSendingAwsLambdaEventHook")};async function Cp(n,e){g("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:c=!1,binaryMediaTypes:u}=e.route.handler.options;if(!t)throw new f("awsAccessKeyId is not set in the handler options");if(!r)throw new f("secretAccessKey is not set in the handler options");if(!o)throw new f("region is not set in the handler options");if(!i)throw new f("functionName is not set in the handler options");let l=new mn({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(uu(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,m]=await kp(n,{binaryMediaTypes:u}),{options:h}=e.route.handler,w;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?w=_p(n,e):w=await Ap(n,e,{useAwsResourcePathStyle:c}),uu("Calling onSendingAwsLambdaEvent hook");let b=await Tp(n,e,w);b.body=p,b.isBase64Encoded=m;let P=await l.fetch(d,{body:JSON.stringify(b)});try{return Op(P)}catch(N){if(N instanceof Ue){let A=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&N.traceId?{AMZN_TRACE_ID_HEADER:N.traceId}:void 0;return T.internalServerError(n,e,void 0,A)}throw N}}s(Cp,"awsLambdaHandler");async function Op(n){let e;try{e=await n.json()}catch{throw new Ue("Lambda response did not contain valid JSON",n.headers)}if(n.status!==200)throw e&&typeof e=="object"&&"message"in e&&typeof e.message=="string"?new Ue(e.message,n.headers):new Ue(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Ue(e.errorMessage,n.headers);if(!e||typeof e!="object"||!("statusCode"in e)||typeof e.statusCode!="number")return new Response(JSON.stringify(e),{status:n.status,headers:{"content-type":"application/json"}});let t=new Headers;if("headers"in e&&e.headers){if(typeof e.headers!="object")throw new Ue(`Response headers must be an object. Received ${typeof e.headers}`,n.headers);for(let[o,i]of Object.entries(e.headers))t.set(o,i)}if("cookies"in e&&e.cookies){if(!Array.isArray(e.cookies))throw new Ue(`Response cookies must be an array. Received ${typeof e.cookies}`,n.headers);t.set("cookie",e.cookies.join(";"))}let r;if("isBase64Encoded"in e&&typeof e.isBase64Encoded!="boolean")throw new Ue(`Response property isBase64Encoded must be a boolean. Received ${typeof e.isBase64Encoded}`,n.headers);if("isBase64Encoded"in e&&e.isBase64Encoded===!0){if(!("body"in e))throw new Ue("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Ue("Response was set to base64 encoded but body was not a string",n.headers);r=au(e.body)}else"body"in e&&typeof e.body=="string"?r=e.statusCode===204&&e.body===""?null:e.body:"body"in e&&e.body!==null&&e.body!==void 0?r=JSON.stringify(e.body):r=null;if(r!==null&&"bodyEncoding"in e){if(typeof e.bodyEncoding!="string"||!(e.bodyEncoding==="gzip"||e.bodyEncoding==="deflate"))throw new Ue(`Response property bodyEncoding can only be set to 'gzip' or 'deflate'. Received ${e.bodyEncoding}`,n.headers);let o=new Blob([r]).stream().pipeThrough(new DecompressionStream(e.bodyEncoding));r=await new Response(o).arrayBuffer()}return new Response(r,{headers:t,status:e.statusCode})}s(Op,"getResponse");async function Ap(n,e,{useAwsResourcePathStyle:t}){let r={},o={};n.headers.forEach((l,d)=>{r[d]=l,o[d]=[l]});let i=n.query,a={};for(let[l,d]of Object.entries(i))a[l]||(a[l]=[]),a[l].push(d);let c=new URL(n.url);return{version:"1.0",resource:c.pathname,path:c.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:c.hostname,domainPrefix:null,extendedRequestId:e.requestId,httpMethod:n.method,identity:{accessKey:null,accountId:null,caller:null,cognitoAuthenticationProvider:null,cognitoAuthenticationType:null,cognitoIdentityId:null,cognitoIdentityPoolId:null,principalOrgId:null,sourceIp:n.headers.get("CF-Connecting-IP"),user:null,userAgent:n.headers.get("user-agent"),userArn:null,clientCert:{clientCertPem:null,subjectDN:null,issuerDN:null,serialNumber:null,validity:{notBefore:null,notAfter:null}}},path:c.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Bi(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Np(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(Ap,"buildEventVersion1");function _p(n,e){let t={};n.headers.forEach((i,a)=>{t[a]=i});let r=new URL(n.url);return{version:"2.0",routeKey:null,rawPath:r.pathname,rawQueryString:r.search,cookies:[],headers:t,queryStringParameters:n.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:r.hostname,domainPrefix:null,http:{method:n.method,path:r.pathname,protocol:"HTTP/1.1",sourceIp:n.headers.get("CF-Connecting-IP"),userAgent:n.headers.get("user-agent")},requestId:e.requestId,routeKey:null,stage:null,time:Bi(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(_p,"buildEventVersion2");async function kp(n,{binaryMediaTypes:e}){let t,r=!1,o=n.headers.get("content-type");if(n.method==="GET"||n.method==="HEAD")t=null;else if(e&&o&&Lp(e,o)){let i=await n.arrayBuffer();t=cu(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(kp,"getBodyResult");function Lp(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(Lp,"matchesContentType");function Np(n,e=!1){if(!e)return n;let t=Hi(n),r=ru(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(Np,"getResourcePath");var Mp=[502,503,504];async function gn(n,e){if(Mp.includes(n.status)){let t=ne.getLogger(e),o=await n.clone().text(),i={};for(let[a,c]of n.headers)i[a]=c;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:i})}}s(gn,"logBadGatewayResponses");var Gi;function St(n){if(Gi===void 0){let t=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Gi=t}return n.log[Gi]}s(St,"getHandlerUserLogFunction");async function Dp(n,e){g("handler.open-api");let t=y.instance.build.BUILD_ID,{buildAssetsUrl:r}=y.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new f("Open API Spec Handler must have 'openApiFilePath' specified");let a=Zp(i);if(!a.isValid)throw new f(a.error);let c=`${r}/${t}${i.substring(1)}`,u=await j.fetch(c,{method:n.method,body:n.body,headers:n.headers});if(u.status!==200)return T.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(u.body,{headers:{"content-type":"application/json","content-encoding":u.headers.get("content-encoding")||"",vary:"Accept-Encoding"},status:u.status,statusText:u.statusText});return gn(l,e),l}s(Dp,"openApiSpecHandler");var Zp=s(n=>n.startsWith("./")?n.startsWith("./config")?n.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 qp(n,e){g("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new f("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}s(qp,"redirectHandler");async function $p(n){if(g("handler.zuplo-service-proxy"),Object.entries(n.params).length!==1)throw new f("The service proxy handler only supports one wildcard path parameter. Change your url to something like '/service/{path}'");let e=new URL(n.params.path,y.instance.zuploEdgeApiUrl),t=new Headers(n.headers);return t.set("Authorization",`Bearer ${y.instance.authApiJWT}`),j.fetch(e,{method:n.method,headers:t,body:n.body})}s($p,"zuploServiceProxy");function Up(n,e){let t=n.endsWith("/"),r=e.startsWith("/");return t&&r?`${n.substring(0,n.length-1)}${e}`:!t&&!r?`${n}/${e}`:`${n}${e}`}s(Up,"join");async function Hp(n,e){g("handler.url-forward");let t=St(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i;if(y.instance.build.COMPATIBILITY_FLAGS.useForwardRedirectsPropOnUrlForwardHandler?i=r.followRedirects===!0?"follow":"manual":typeof r.followRedirects<"u"&&g("handler.url-forward.follow-redirects"),!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a=Tt(e),c=new URL(n.url),u=r.__rewriteFunction(n,a),l=Up(u,c.pathname),d=o?`${l}${c.search}`:l.toString(),p=Date.now();t(`URL Forwarding to '${d}'`);let m=await fetch(d,{method:n.method,body:n.body,headers:n.headers,redirect:i}),h=Date.now()-p;return t(`URL Forward received response ${m.status} - ${m.statusText} in ${h}ms`),gn(m,e),m}s(Hp,"urlForwardHandler");var Fp=s((n,e)=>{let t=new URL(n),r=new URL(e);for(let[o,i]of r.searchParams.entries())t.searchParams.append(o,i);return t.toString()},"addQuery");async function jp(n,e){g("handler.url-rewrite");let t=St(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new f("Invalid options for this route");let a=Tt(e),c=r.__rewriteFunction(n,a),u=o?Fp(c,n.url):c,l=Date.now();t(`URL Rewriting to '${u}'`);let d=await fetch(u.toString(),{method:n.method,body:n.body,headers:n.headers,redirect:i?"follow":"manual"}),p=Date.now()-l;return t(`URL Rewrite received response ${d.status} - ${d.statusText} in ${p}ms`),gn(d,e),d}s(jp,"urlRewriteHandler");async function zp(n,e){g("handler.websocket");let t=e.route.handler.options,r=St(e);if(!t||!t.rewritePattern)throw new f("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new f("Invalid options for this route");let i=Tt(e),a=t.__rewriteFunction(n,i),c=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let u=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(u.status!==101||!u.webSocket){let d=await u.text(),p=`WebSocket connection error - ${u.status}: ${u.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-c;return r(`WebSocket connected, received response ${u.status} - ${u.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:u.webSocket})}s(zp,"webSocketHandler");var Vi=s((n,e)=>n.map((r,o)=>{let i;if(typeof r.module=="object"&&(i=r.module[r.export]),!i||typeof i!="function"){let a=e==="inbound"?"WebSocketInboundPolicy":"WebSocketOutboundPolicy",c=`policy in position: ${o+1}, export name: ${r.export}`;throw new f(`${a} - Websocket policy must be a valid function (${c})`)}return i}),"getWebSocketPolicyFunctions"),du=s(async(n,e,t,r,o,i)=>{let a=n.data;if(i&&i.length>0){let c=[...i];for(;c.length>0;){let u=c.shift();if(!u)return a;if(a=await u(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function pu(n,e,t,r,o){n.addEventListener("close",()=>{e.close()}),n.addEventListener("error",i=>{r.log.error("WebSocket error: ",i),e.send(JSON.stringify(i))}),n.addEventListener("message",i=>{try{let c=s(async u=>{let l=await du(u,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(c)}catch(a){r.log.error(a)}})}s(pu,"wireUpListeners");async function Bp(n,e){g("handler.websocket-pipeline");let t=e.route.handler.options,r=St(e);if(!t||!t.rewritePattern)throw new f("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return T.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new f("Invalid options for this route");let i=Tt(e),a=t.__rewriteFunction(n,i),c=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let u=await fetch(a,{method:n.method,headers:n.headers,body:n.body});if(u.status!==101||!u.webSocket){let P=await u.text(),N=`WebSocket connection error - ${u.status}: ${u.statusText}, content: '${P}'`;throw new Error(N)}let l=new WebSocketPair,[d,p]=Object.values(l),m=Date.now()-c;r(`WebSocket connected, received response ${u.status} - ${u.statusText} in ${m}ms`);let h=u.webSocket;h.accept(),p.accept();let w=t.policies&&t.policies.inbound?Vi(t.policies.inbound,"inbound"):[],b=t.policies&&t.policies.outbound?Vi(t.policies.outbound,"outbound"):[];return pu(p,h,n,e,w),pu(h,p,n,e,b),new Response(null,{status:101,webSocket:d})}s(Bp,"webSocketPipelineHandler");var pe;(function(n){n.assertEqual=o=>o;function e(o){}s(e,"assertIs"),n.assertIs=e;function t(o){throw new Error}s(t,"assertNever"),n.assertNever=t,n.arrayToEnum=o=>{let i={};for(let a of o)i[a]=a;return i},n.getValidEnumValues=o=>{let i=n.objectKeys(o).filter(c=>typeof o[o[c]]!="number"),a={};for(let c of i)a[c]=o[c];return n.objectValues(a)},n.objectValues=o=>n.objectKeys(o).map(function(i){return o[i]}),n.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let i=[];for(let a in o)Object.prototype.hasOwnProperty.call(o,a)&&i.push(a);return i},n.find=(o,i)=>{for(let a of o)if(i(a))return a},n.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&isFinite(o)&&Math.floor(o)===o;function r(o,i=" | "){return o.map(a=>typeof a=="string"?`'${a}'`:a).join(i)}s(r,"joinValues"),n.joinValues=r,n.jsonStringifyReplacer=(o,i)=>typeof i=="bigint"?i.toString():i})(pe||(pe={}));var Ji;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Ji||(Ji={}));var z=pe.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),pt=s(n=>{switch(typeof n){case"undefined":return z.undefined;case"string":return z.string;case"number":return isNaN(n)?z.nan:z.number;case"boolean":return z.boolean;case"function":return z.function;case"bigint":return z.bigint;case"symbol":return z.symbol;case"object":return Array.isArray(n)?z.array:n===null?z.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?z.promise:typeof Map<"u"&&n instanceof Map?z.map:typeof Set<"u"&&n instanceof Set?z.set:typeof Date<"u"&&n instanceof Date?z.date:z.object;default:return z.unknown}},"getParsedType"),L=pe.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Gp=s(n=>JSON.stringify(n,null,2).replace(/"([^"]+)":/g,"$1:"),"quotelessJson"),He=class n extends Error{static{s(this,"ZodError")}get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(i){return i.message},r={_errors:[]},o=s(i=>{for(let a of i.issues)if(a.code==="invalid_union")a.unionErrors.map(o);else if(a.code==="invalid_return_type")o(a.returnTypeError);else if(a.code==="invalid_arguments")o(a.argumentsError);else if(a.path.length===0)r._errors.push(t(a));else{let c=r,u=0;for(;u<a.path.length;){let l=a.path[u];u===a.path.length-1?(c[l]=c[l]||{_errors:[]},c[l]._errors.push(t(a))):c[l]=c[l]||{_errors:[]},c=c[l],u++}}},"processError");return o(this),r}static assert(e){if(!(e instanceof n))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,pe.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},r=[];for(let o of this.issues)o.path.length>0?(t[o.path[0]]=t[o.path[0]]||[],t[o.path[0]].push(e(o))):r.push(e(o));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}};He.create=n=>new He(n);var bn=s((n,e)=>{let t;switch(n.code){case L.invalid_type:n.received===z.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case L.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,pe.jsonStringifyReplacer)}`;break;case L.unrecognized_keys:t=`Unrecognized key(s) in object: ${pe.joinValues(n.keys,", ")}`;break;case L.invalid_union:t="Invalid input";break;case L.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${pe.joinValues(n.options)}`;break;case L.invalid_enum_value:t=`Invalid enum value. Expected ${pe.joinValues(n.options)}, received '${n.received}'`;break;case L.invalid_arguments:t="Invalid function arguments";break;case L.invalid_return_type:t="Invalid function return type";break;case L.invalid_date:t="Invalid date";break;case L.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:pe.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case L.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case L.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case L.custom:t="Invalid input";break;case L.invalid_intersection_types:t="Intersection results could not be merged";break;case L.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case L.not_finite:t="Number must be finite";break;default:t=e.defaultError,pe.assertNever(n)}return{message:t}},"errorMap"),hu=bn;function Vp(n){hu=n}s(Vp,"setErrorMap");function io(){return hu}s(io,"getErrorMap");var so=s(n=>{let{data:e,path:t,errorMaps:r,issueData:o}=n,i=[...t,...o.path||[]],a={...o,path:i};if(o.message!==void 0)return{...o,path:i,message:o.message};let c="",u=r.filter(l=>!!l).slice().reverse();for(let l of u)c=l(a,{data:e,defaultError:c}).message;return{...o,path:i,message:c}},"makeIssue"),Wp=[];function Z(n,e){let t=io(),r=so({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===bn?void 0:bn].filter(o=>!!o)});n.common.issues.push(r)}s(Z,"addIssueToContext");var Ae=class n{static{s(this,"ParseStatus")}constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let r=[];for(let o of t){if(o.status==="aborted")return ee;o.status==="dirty"&&e.dirty(),r.push(o.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){let r=[];for(let o of t){let i=await o.key,a=await o.value;r.push({key:i,value:a})}return n.mergeObjectSync(e,r)}static mergeObjectSync(e,t){let r={};for(let o of t){let{key:i,value:a}=o;if(i.status==="aborted"||a.status==="aborted")return ee;i.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),i.value!=="__proto__"&&(typeof a.value<"u"||o.alwaysSet)&&(r[i.value]=a.value)}return{status:e.value,value:r}}},ee=Object.freeze({status:"aborted"}),yn=s(n=>({status:"dirty",value:n}),"DIRTY"),Ne=s(n=>({status:"valid",value:n}),"OK"),Ki=s(n=>n.status==="aborted","isAborted"),Qi=s(n=>n.status==="dirty","isDirty"),$t=s(n=>n.status==="valid","isValid"),lr=s(n=>typeof Promise<"u"&&n instanceof Promise,"isAsync");function ao(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}s(ao,"__classPrivateFieldGet");function yu(n,e,t,r,o){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!o)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!o:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?o.call(n,t):o?o.value=t:e.set(n,t),t}s(yu,"__classPrivateFieldSet");var J;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})(J||(J={}));var cr,ur,Ve=class{static{s(this,"ParseInputLazyPath")}constructor(e,t,r,o){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=o}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},mu=s((n,e)=>{if($t(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new He(n.common.issues);return this._error=t,this._error}}},"handleResult");function re(n){if(!n)return{};let{errorMap:e,invalid_type_error:t,required_error:r,description:o}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:s((a,c)=>{var u,l;let{message:d}=n;return a.code==="invalid_enum_value"?{message:d??c.defaultError}:typeof c.data>"u"?{message:(u=d??r)!==null&&u!==void 0?u:c.defaultError}:a.code!=="invalid_type"?{message:c.defaultError}:{message:(l=d??t)!==null&&l!==void 0?l:c.defaultError}},"customMap"),description:o}}s(re,"processCreateParams");var oe=class{static{s(this,"ZodType")}get description(){return this._def.description}_getType(e){return pt(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ae,ctx:{common:e.parent.common,data:e.data,parsedType:pt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(lr(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){var r;let o={common:{issues:[],async:(r=t?.async)!==null&&r!==void 0?r:!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)},i=this._parseSync({data:e,path:o.path,parent:o});return mu(o,i)}"~validate"(e){var t,r;let o={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)};if(!this["~standard"].async)try{let i=this._parseSync({data:e,path:[],parent:o});return $t(i)?{value:i.value}:{issues:o.common.issues}}catch(i){!((r=(t=i?.message)===null||t===void 0?void 0:t.toLowerCase())===null||r===void 0)&&r.includes("encountered")&&(this["~standard"].async=!0),o.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:o}).then(i=>$t(i)?{value:i.value}:{issues:o.common.issues})}async parseAsync(e,t){let r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){let r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:pt(e)},o=this._parse({data:e,path:r.path,parent:r}),i=await(lr(o)?o:Promise.resolve(o));return mu(r,i)}refine(e,t){let r=s(o=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(o):t,"getIssueProperties");return this._refinement((o,i)=>{let a=e(o),c=s(()=>i.addIssue({code:L.custom,...r(o)}),"setError");return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(c(),!1)):a?!0:(c(),!1)})}refinement(e,t){return this._refinement((r,o)=>e(r)?!0:(o.addIssue(typeof t=="function"?t(r,o):t),!1))}_refinement(e){return new Fe({schema:this,typeName:X.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:s(t=>this["~validate"](t),"validate")}}optional(){return Ge.create(this,this._def)}nullable(){return ot.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ft.create(this)}promise(){return At.create(this,this._def)}or(e){return Gt.create([this,e],this._def)}and(e){return Vt.create(this,e,this._def)}transform(e){return new Fe({...re(this._def),schema:this,typeName:X.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Yt({...re(this._def),innerType:this,defaultValue:t,typeName:X.ZodDefault})}brand(){return new dr({typeName:X.ZodBranded,type:this,...re(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Xt({...re(this._def),innerType:this,catchValue:t,typeName:X.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return pr.create(this,e)}readonly(){return en.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Jp=/^c[^\s-]{8,}$/i,Kp=/^[0-9a-z]+$/,Qp=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Yp=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Xp=/^[a-z0-9_-]{21}$/i,em=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,tm=/^[-+]?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)?)??$/,nm=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,rm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Wi,om=/^(?:(?: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])$/,im=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,sm=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,am=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,cm=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,um=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,bu="((\\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])))",lm=new RegExp(`^${bu}$`);function wu(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);let t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}s(wu,"timeRegexSource");function dm(n){return new RegExp(`^${wu(n)}$`)}s(dm,"timeRegex");function Ru(n){let e=`${bu}T${wu(n)}`,t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}s(Ru,"datetimeRegex");function pm(n,e){return!!((e==="v4"||!e)&&om.test(n)||(e==="v6"||!e)&&sm.test(n))}s(pm,"isValidIP");function mm(n,e){if(!em.test(n))return!1;try{let[t]=n.split("."),r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),o=JSON.parse(atob(r));return!(typeof o!="object"||o===null||!o.typ||!o.alg||e&&o.alg!==e)}catch{return!1}}s(mm,"isValidJWT");function fm(n,e){return!!((e==="v4"||!e)&&im.test(n)||(e==="v6"||!e)&&am.test(n))}s(fm,"isValidCidr");var Ct=class n extends oe{static{s(this,"ZodString")}_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==z.string){let i=this._getOrReturnCtx(e);return Z(i,{code:L.invalid_type,expected:z.string,received:i.parsedType}),ee}let r=new Ae,o;for(let i of this._def.checks)if(i.kind==="min")e.data.length<i.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:L.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="max")e.data.length>i.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:L.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!1,message:i.message}),r.dirty());else if(i.kind==="length"){let a=e.data.length>i.value,c=e.data.length<i.value;(a||c)&&(o=this._getOrReturnCtx(e,o),a?Z(o,{code:L.too_big,maximum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}):c&&Z(o,{code:L.too_small,minimum:i.value,type:"string",inclusive:!0,exact:!0,message:i.message}),r.dirty())}else if(i.kind==="email")nm.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"email",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="emoji")Wi||(Wi=new RegExp(rm,"u")),Wi.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"emoji",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="uuid")Yp.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"uuid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="nanoid")Xp.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"nanoid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid")Jp.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="cuid2")Kp.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cuid2",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="ulid")Qp.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ulid",code:L.invalid_string,message:i.message}),r.dirty());else if(i.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),Z(o,{validation:"url",code:L.invalid_string,message:i.message}),r.dirty()}else i.kind==="regex"?(i.regex.lastIndex=0,i.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"regex",code:L.invalid_string,message:i.message}),r.dirty())):i.kind==="trim"?e.data=e.data.trim():i.kind==="includes"?e.data.includes(i.value,i.position)||(o=this._getOrReturnCtx(e,o),Z(o,{code:L.invalid_string,validation:{includes:i.value,position:i.position},message:i.message}),r.dirty()):i.kind==="toLowerCase"?e.data=e.data.toLowerCase():i.kind==="toUpperCase"?e.data=e.data.toUpperCase():i.kind==="startsWith"?e.data.startsWith(i.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:L.invalid_string,validation:{startsWith:i.value},message:i.message}),r.dirty()):i.kind==="endsWith"?e.data.endsWith(i.value)||(o=this._getOrReturnCtx(e,o),Z(o,{code:L.invalid_string,validation:{endsWith:i.value},message:i.message}),r.dirty()):i.kind==="datetime"?Ru(i).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:L.invalid_string,validation:"datetime",message:i.message}),r.dirty()):i.kind==="date"?lm.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:L.invalid_string,validation:"date",message:i.message}),r.dirty()):i.kind==="time"?dm(i).test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{code:L.invalid_string,validation:"time",message:i.message}),r.dirty()):i.kind==="duration"?tm.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"duration",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="ip"?pm(e.data,i.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"ip",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="jwt"?mm(e.data,i.alg)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"jwt",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="cidr"?fm(e.data,i.version)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"cidr",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="base64"?cm.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64",code:L.invalid_string,message:i.message}),r.dirty()):i.kind==="base64url"?um.test(e.data)||(o=this._getOrReturnCtx(e,o),Z(o,{validation:"base64url",code:L.invalid_string,message:i.message}),r.dirty()):pe.assertNever(i);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(o=>e.test(o),{validation:t,code:L.invalid_string,...J.errToObj(r)})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...J.errToObj(e)})}url(e){return this._addCheck({kind:"url",...J.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...J.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...J.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...J.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...J.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...J.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...J.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...J.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...J.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...J.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...J.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...J.errToObj(e)})}datetime(e){var t,r;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(t=e?.offset)!==null&&t!==void 0?t:!1,local:(r=e?.local)!==null&&r!==void 0?r:!1,...J.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...J.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...J.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...J.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...J.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...J.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...J.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...J.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...J.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...J.errToObj(t)})}nonempty(e){return this.min(1,J.errToObj(e))}trim(){return new n({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new n({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Ct.create=n=>{var e;return new Ct({checks:[],typeName:X.ZodString,coerce:(e=n?.coerce)!==null&&e!==void 0?e:!1,...re(n)})};function gm(n,e){let t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,o=t>r?t:r,i=parseInt(n.toFixed(o).replace(".","")),a=parseInt(e.toFixed(o).replace(".",""));return i%a/Math.pow(10,o)}s(gm,"floatSafeRemainder");var Ut=class n extends oe{static{s(this,"ZodNumber")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==z.number){let i=this._getOrReturnCtx(e);return Z(i,{code:L.invalid_type,expected:z.number,received:i.parsedType}),ee}let r,o=new Ae;for(let i of this._def.checks)i.kind==="int"?pe.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),Z(r,{code:L.invalid_type,expected:"integer",received:"float",message:i.message}),o.dirty()):i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Z(r,{code:L.too_small,minimum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Z(r,{code:L.too_big,maximum:i.value,type:"number",inclusive:i.inclusive,exact:!1,message:i.message}),o.dirty()):i.kind==="multipleOf"?gm(e.data,i.value)!==0&&(r=this._getOrReturnCtx(e,r),Z(r,{code:L.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):i.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),Z(r,{code:L.not_finite,message:i.message}),o.dirty()):pe.assertNever(i);return{status:o.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,J.toString(t))}gt(e,t){return this.setLimit("min",e,!1,J.toString(t))}lte(e,t){return this.setLimit("max",e,!0,J.toString(t))}lt(e,t){return this.setLimit("max",e,!1,J.toString(t))}setLimit(e,t,r,o){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:J.toString(o)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:J.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:J.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:J.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:J.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:J.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&pe.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Ut.create=n=>new Ut({checks:[],typeName:X.ZodNumber,coerce:n?.coerce||!1,...re(n)});var Ht=class n extends oe{static{s(this,"ZodBigInt")}constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==z.bigint)return this._getInvalidInput(e);let r,o=new Ae;for(let i of this._def.checks)i.kind==="min"?(i.inclusive?e.data<i.value:e.data<=i.value)&&(r=this._getOrReturnCtx(e,r),Z(r,{code:L.too_small,type:"bigint",minimum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="max"?(i.inclusive?e.data>i.value:e.data>=i.value)&&(r=this._getOrReturnCtx(e,r),Z(r,{code:L.too_big,type:"bigint",maximum:i.value,inclusive:i.inclusive,message:i.message}),o.dirty()):i.kind==="multipleOf"?e.data%i.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),Z(r,{code:L.not_multiple_of,multipleOf:i.value,message:i.message}),o.dirty()):pe.assertNever(i);return{status:o.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return Z(t,{code:L.invalid_type,expected:z.bigint,received:t.parsedType}),ee}gte(e,t){return this.setLimit("min",e,!0,J.toString(t))}gt(e,t){return this.setLimit("min",e,!1,J.toString(t))}lte(e,t){return this.setLimit("max",e,!0,J.toString(t))}lt(e,t){return this.setLimit("max",e,!1,J.toString(t))}setLimit(e,t,r,o){return new n({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:J.toString(o)}]})}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:J.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:J.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:J.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:J.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:J.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Ht.create=n=>{var e;return new Ht({checks:[],typeName:X.ZodBigInt,coerce:(e=n?.coerce)!==null&&e!==void 0?e:!1,...re(n)})};var Ft=class extends oe{static{s(this,"ZodBoolean")}_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==z.boolean){let r=this._getOrReturnCtx(e);return Z(r,{code:L.invalid_type,expected:z.boolean,received:r.parsedType}),ee}return Ne(e.data)}};Ft.create=n=>new Ft({typeName:X.ZodBoolean,coerce:n?.coerce||!1,...re(n)});var jt=class n extends oe{static{s(this,"ZodDate")}_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==z.date){let i=this._getOrReturnCtx(e);return Z(i,{code:L.invalid_type,expected:z.date,received:i.parsedType}),ee}if(isNaN(e.data.getTime())){let i=this._getOrReturnCtx(e);return Z(i,{code:L.invalid_date}),ee}let r=new Ae,o;for(let i of this._def.checks)i.kind==="min"?e.data.getTime()<i.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:L.too_small,message:i.message,inclusive:!0,exact:!1,minimum:i.value,type:"date"}),r.dirty()):i.kind==="max"?e.data.getTime()>i.value&&(o=this._getOrReturnCtx(e,o),Z(o,{code:L.too_big,message:i.message,inclusive:!0,exact:!1,maximum:i.value,type:"date"}),r.dirty()):pe.assertNever(i);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new n({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:J.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:J.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};jt.create=n=>new jt({checks:[],coerce:n?.coerce||!1,typeName:X.ZodDate,...re(n)});var wn=class extends oe{static{s(this,"ZodSymbol")}_parse(e){if(this._getType(e)!==z.symbol){let r=this._getOrReturnCtx(e);return Z(r,{code:L.invalid_type,expected:z.symbol,received:r.parsedType}),ee}return Ne(e.data)}};wn.create=n=>new wn({typeName:X.ZodSymbol,...re(n)});var zt=class extends oe{static{s(this,"ZodUndefined")}_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return Z(r,{code:L.invalid_type,expected:z.undefined,received:r.parsedType}),ee}return Ne(e.data)}};zt.create=n=>new zt({typeName:X.ZodUndefined,...re(n)});var Bt=class extends oe{static{s(this,"ZodNull")}_parse(e){if(this._getType(e)!==z.null){let r=this._getOrReturnCtx(e);return Z(r,{code:L.invalid_type,expected:z.null,received:r.parsedType}),ee}return Ne(e.data)}};Bt.create=n=>new Bt({typeName:X.ZodNull,...re(n)});var Ot=class extends oe{static{s(this,"ZodAny")}constructor(){super(...arguments),this._any=!0}_parse(e){return Ne(e.data)}};Ot.create=n=>new Ot({typeName:X.ZodAny,...re(n)});var mt=class extends oe{static{s(this,"ZodUnknown")}constructor(){super(...arguments),this._unknown=!0}_parse(e){return Ne(e.data)}};mt.create=n=>new mt({typeName:X.ZodUnknown,...re(n)});var Je=class extends oe{static{s(this,"ZodNever")}_parse(e){let t=this._getOrReturnCtx(e);return Z(t,{code:L.invalid_type,expected:z.never,received:t.parsedType}),ee}};Je.create=n=>new Je({typeName:X.ZodNever,...re(n)});var Rn=class extends oe{static{s(this,"ZodVoid")}_parse(e){if(this._getType(e)!==z.undefined){let r=this._getOrReturnCtx(e);return Z(r,{code:L.invalid_type,expected:z.void,received:r.parsedType}),ee}return Ne(e.data)}};Rn.create=n=>new Rn({typeName:X.ZodVoid,...re(n)});var ft=class n extends oe{static{s(this,"ZodArray")}_parse(e){let{ctx:t,status:r}=this._processInputParams(e),o=this._def;if(t.parsedType!==z.array)return Z(t,{code:L.invalid_type,expected:z.array,received:t.parsedType}),ee;if(o.exactLength!==null){let a=t.data.length>o.exactLength.value,c=t.data.length<o.exactLength.value;(a||c)&&(Z(t,{code:a?L.too_big:L.too_small,minimum:c?o.exactLength.value:void 0,maximum:a?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),r.dirty())}if(o.minLength!==null&&t.data.length<o.minLength.value&&(Z(t,{code:L.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),r.dirty()),o.maxLength!==null&&t.data.length>o.maxLength.value&&(Z(t,{code:L.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((a,c)=>o.type._parseAsync(new Ve(t,a,t.path,c)))).then(a=>Ae.mergeArray(r,a));let i=[...t.data].map((a,c)=>o.type._parseSync(new Ve(t,a,t.path,c)));return Ae.mergeArray(r,i)}get element(){return this._def.type}min(e,t){return new n({...this._def,minLength:{value:e,message:J.toString(t)}})}max(e,t){return new n({...this._def,maxLength:{value:e,message:J.toString(t)}})}length(e,t){return new n({...this._def,exactLength:{value:e,message:J.toString(t)}})}nonempty(e){return this.min(1,e)}};ft.create=(n,e)=>new ft({type:n,minLength:null,maxLength:null,exactLength:null,typeName:X.ZodArray,...re(e)});function hn(n){if(n instanceof De){let e={};for(let t in n.shape){let r=n.shape[t];e[t]=Ge.create(hn(r))}return new De({...n._def,shape:s(()=>e,"shape")})}else return n instanceof ft?new ft({...n._def,type:hn(n.element)}):n instanceof Ge?Ge.create(hn(n.unwrap())):n instanceof ot?ot.create(hn(n.unwrap())):n instanceof rt?rt.create(n.items.map(e=>hn(e))):n}s(hn,"deepPartialify");var De=class n extends oe{static{s(this,"ZodObject")}constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=pe.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==z.object){let l=this._getOrReturnCtx(e);return Z(l,{code:L.invalid_type,expected:z.object,received:l.parsedType}),ee}let{status:r,ctx:o}=this._processInputParams(e),{shape:i,keys:a}=this._getCached(),c=[];if(!(this._def.catchall instanceof Je&&this._def.unknownKeys==="strip"))for(let l in o.data)a.includes(l)||c.push(l);let u=[];for(let l of a){let d=i[l],p=o.data[l];u.push({key:{status:"valid",value:l},value:d._parse(new Ve(o,p,o.path,l)),alwaysSet:l in o.data})}if(this._def.catchall instanceof Je){let l=this._def.unknownKeys;if(l==="passthrough")for(let d of c)u.push({key:{status:"valid",value:d},value:{status:"valid",value:o.data[d]}});else if(l==="strict")c.length>0&&(Z(o,{code:L.unrecognized_keys,keys:c}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let l=this._def.catchall;for(let d of c){let p=o.data[d];u.push({key:{status:"valid",value:d},value:l._parse(new Ve(o,p,o.path,d)),alwaysSet:d in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let l=[];for(let d of u){let p=await d.key,m=await d.value;l.push({key:p,value:m,alwaysSet:d.alwaysSet})}return l}).then(l=>Ae.mergeObjectSync(r,l)):Ae.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return J.errToObj,new n({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:s((t,r)=>{var o,i,a,c;let u=(a=(i=(o=this._def).errorMap)===null||i===void 0?void 0:i.call(o,t,r).message)!==null&&a!==void 0?a:r.defaultError;return t.code==="unrecognized_keys"?{message:(c=J.errToObj(e).message)!==null&&c!==void 0?c:u}:{message:u}},"errorMap")}:{}})}strip(){return new n({...this._def,unknownKeys:"strip"})}passthrough(){return new n({...this._def,unknownKeys:"passthrough"})}extend(e){return new n({...this._def,shape:s(()=>({...this._def.shape(),...e}),"shape")})}merge(e){return new n({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:s(()=>({...this._def.shape(),...e._def.shape()}),"shape"),typeName:X.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new n({...this._def,catchall:e})}pick(e){let t={};return pe.objectKeys(e).forEach(r=>{e[r]&&this.shape[r]&&(t[r]=this.shape[r])}),new n({...this._def,shape:s(()=>t,"shape")})}omit(e){let t={};return pe.objectKeys(this.shape).forEach(r=>{e[r]||(t[r]=this.shape[r])}),new n({...this._def,shape:s(()=>t,"shape")})}deepPartial(){return hn(this)}partial(e){let t={};return pe.objectKeys(this.shape).forEach(r=>{let o=this.shape[r];e&&!e[r]?t[r]=o:t[r]=o.optional()}),new n({...this._def,shape:s(()=>t,"shape")})}required(e){let t={};return pe.objectKeys(this.shape).forEach(r=>{if(e&&!e[r])t[r]=this.shape[r];else{let i=this.shape[r];for(;i instanceof Ge;)i=i._def.innerType;t[r]=i}}),new n({...this._def,shape:s(()=>t,"shape")})}keyof(){return vu(pe.objectKeys(this.shape))}};De.create=(n,e)=>new De({shape:s(()=>n,"shape"),unknownKeys:"strip",catchall:Je.create(),typeName:X.ZodObject,...re(e)});De.strictCreate=(n,e)=>new De({shape:s(()=>n,"shape"),unknownKeys:"strict",catchall:Je.create(),typeName:X.ZodObject,...re(e)});De.lazycreate=(n,e)=>new De({shape:n,unknownKeys:"strip",catchall:Je.create(),typeName:X.ZodObject,...re(e)});var Gt=class extends oe{static{s(this,"ZodUnion")}_parse(e){let{ctx:t}=this._processInputParams(e),r=this._def.options;function o(i){for(let c of i)if(c.result.status==="valid")return c.result;for(let c of i)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;let a=i.map(c=>new He(c.ctx.common.issues));return Z(t,{code:L.invalid_union,unionErrors:a}),ee}if(s(o,"handleResults"),t.common.async)return Promise.all(r.map(async i=>{let a={...t,common:{...t.common,issues:[]},parent:null};return{result:await i._parseAsync({data:t.data,path:t.path,parent:a}),ctx:a}})).then(o);{let i,a=[];for(let u of r){let l={...t,common:{...t.common,issues:[]},parent:null},d=u._parseSync({data:t.data,path:t.path,parent:l});if(d.status==="valid")return d;d.status==="dirty"&&!i&&(i={result:d,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(i)return t.common.issues.push(...i.ctx.common.issues),i.result;let c=a.map(u=>new He(u));return Z(t,{code:L.invalid_union,unionErrors:c}),ee}}get options(){return this._def.options}};Gt.create=(n,e)=>new Gt({options:n,typeName:X.ZodUnion,...re(e)});var dt=s(n=>n instanceof Wt?dt(n.schema):n instanceof Fe?dt(n.innerType()):n instanceof Jt?[n.value]:n instanceof Kt?n.options:n instanceof Qt?pe.objectValues(n.enum):n instanceof Yt?dt(n._def.innerType):n instanceof zt?[void 0]:n instanceof Bt?[null]:n instanceof Ge?[void 0,...dt(n.unwrap())]:n instanceof ot?[null,...dt(n.unwrap())]:n instanceof dr||n instanceof en?dt(n.unwrap()):n instanceof Xt?dt(n._def.innerType):[],"getDiscriminator"),co=class n extends oe{static{s(this,"ZodDiscriminatedUnion")}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.object)return Z(t,{code:L.invalid_type,expected:z.object,received:t.parsedType}),ee;let r=this.discriminator,o=t.data[r],i=this.optionsMap.get(o);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(Z(t,{code:L.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),ee)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,r){let o=new Map;for(let i of t){let a=dt(i.shape[e]);if(!a.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of a){if(o.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);o.set(c,i)}}return new n({typeName:X.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:o,...re(r)})}};function Yi(n,e){let t=pt(n),r=pt(e);if(n===e)return{valid:!0,data:n};if(t===z.object&&r===z.object){let o=pe.objectKeys(e),i=pe.objectKeys(n).filter(c=>o.indexOf(c)!==-1),a={...n,...e};for(let c of i){let u=Yi(n[c],e[c]);if(!u.valid)return{valid:!1};a[c]=u.data}return{valid:!0,data:a}}else if(t===z.array&&r===z.array){if(n.length!==e.length)return{valid:!1};let o=[];for(let i=0;i<n.length;i++){let a=n[i],c=e[i],u=Yi(a,c);if(!u.valid)return{valid:!1};o.push(u.data)}return{valid:!0,data:o}}else return t===z.date&&r===z.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}s(Yi,"mergeValues");var Vt=class extends oe{static{s(this,"ZodIntersection")}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),o=s((i,a)=>{if(Ki(i)||Ki(a))return ee;let c=Yi(i.value,a.value);return c.valid?((Qi(i)||Qi(a))&&t.dirty(),{status:t.value,value:c.data}):(Z(r,{code:L.invalid_intersection_types}),ee)},"handleParsed");return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([i,a])=>o(i,a)):o(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Vt.create=(n,e,t)=>new Vt({left:n,right:e,typeName:X.ZodIntersection,...re(t)});var rt=class n extends oe{static{s(this,"ZodTuple")}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.array)return Z(r,{code:L.invalid_type,expected:z.array,received:r.parsedType}),ee;if(r.data.length<this._def.items.length)return Z(r,{code:L.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ee;!this._def.rest&&r.data.length>this._def.items.length&&(Z(r,{code:L.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let i=[...r.data].map((a,c)=>{let u=this._def.items[c]||this._def.rest;return u?u._parse(new Ve(r,a,r.path,c)):null}).filter(a=>!!a);return r.common.async?Promise.all(i).then(a=>Ae.mergeArray(t,a)):Ae.mergeArray(t,i)}get items(){return this._def.items}rest(e){return new n({...this._def,rest:e})}};rt.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new rt({items:n,typeName:X.ZodTuple,rest:null,...re(e)})};var uo=class n extends oe{static{s(this,"ZodRecord")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.object)return Z(r,{code:L.invalid_type,expected:z.object,received:r.parsedType}),ee;let o=[],i=this._def.keyType,a=this._def.valueType;for(let c in r.data)o.push({key:i._parse(new Ve(r,c,r.path,c)),value:a._parse(new Ve(r,r.data[c],r.path,c)),alwaysSet:c in r.data});return r.common.async?Ae.mergeObjectAsync(t,o):Ae.mergeObjectSync(t,o)}get element(){return this._def.valueType}static create(e,t,r){return t instanceof oe?new n({keyType:e,valueType:t,typeName:X.ZodRecord,...re(r)}):new n({keyType:Ct.create(),valueType:e,typeName:X.ZodRecord,...re(t)})}},vn=class extends oe{static{s(this,"ZodMap")}get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.map)return Z(r,{code:L.invalid_type,expected:z.map,received:r.parsedType}),ee;let o=this._def.keyType,i=this._def.valueType,a=[...r.data.entries()].map(([c,u],l)=>({key:o._parse(new Ve(r,c,r.path,[l,"key"])),value:i._parse(new Ve(r,u,r.path,[l,"value"]))}));if(r.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let u of a){let l=await u.key,d=await u.value;if(l.status==="aborted"||d.status==="aborted")return ee;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(l.value,d.value)}return{status:t.value,value:c}})}else{let c=new Map;for(let u of a){let l=u.key,d=u.value;if(l.status==="aborted"||d.status==="aborted")return ee;(l.status==="dirty"||d.status==="dirty")&&t.dirty(),c.set(l.value,d.value)}return{status:t.value,value:c}}}};vn.create=(n,e,t)=>new vn({valueType:e,keyType:n,typeName:X.ZodMap,...re(t)});var xn=class n extends oe{static{s(this,"ZodSet")}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==z.set)return Z(r,{code:L.invalid_type,expected:z.set,received:r.parsedType}),ee;let o=this._def;o.minSize!==null&&r.data.size<o.minSize.value&&(Z(r,{code:L.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),t.dirty()),o.maxSize!==null&&r.data.size>o.maxSize.value&&(Z(r,{code:L.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),t.dirty());let i=this._def.valueType;function a(u){let l=new Set;for(let d of u){if(d.status==="aborted")return ee;d.status==="dirty"&&t.dirty(),l.add(d.value)}return{status:t.value,value:l}}s(a,"finalizeSet");let c=[...r.data.values()].map((u,l)=>i._parse(new Ve(r,u,r.path,l)));return r.common.async?Promise.all(c).then(u=>a(u)):a(c)}min(e,t){return new n({...this._def,minSize:{value:e,message:J.toString(t)}})}max(e,t){return new n({...this._def,maxSize:{value:e,message:J.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};xn.create=(n,e)=>new xn({valueType:n,minSize:null,maxSize:null,typeName:X.ZodSet,...re(e)});var lo=class n extends oe{static{s(this,"ZodFunction")}constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.function)return Z(t,{code:L.invalid_type,expected:z.function,received:t.parsedType}),ee;function r(c,u){return so({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,io(),bn].filter(l=>!!l),issueData:{code:L.invalid_arguments,argumentsError:u}})}s(r,"makeArgsIssue");function o(c,u){return so({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,io(),bn].filter(l=>!!l),issueData:{code:L.invalid_return_type,returnTypeError:u}})}s(o,"makeReturnsIssue");let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof At){let c=this;return Ne(async function(...u){let l=new He([]),d=await c._def.args.parseAsync(u,i).catch(h=>{throw l.addIssue(r(u,h)),l}),p=await Reflect.apply(a,this,d);return await c._def.returns._def.type.parseAsync(p,i).catch(h=>{throw l.addIssue(o(p,h)),l})})}else{let c=this;return Ne(function(...u){let l=c._def.args.safeParse(u,i);if(!l.success)throw new He([r(u,l.error)]);let d=Reflect.apply(a,this,l.data),p=c._def.returns.safeParse(d,i);if(!p.success)throw new He([o(d,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new n({...this._def,args:rt.create(e).rest(mt.create())})}returns(e){return new n({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,r){return new n({args:e||rt.create([]).rest(mt.create()),returns:t||mt.create(),typeName:X.ZodFunction,...re(r)})}},Wt=class extends oe{static{s(this,"ZodLazy")}get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Wt.create=(n,e)=>new Wt({getter:n,typeName:X.ZodLazy,...re(e)});var Jt=class extends oe{static{s(this,"ZodLiteral")}_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return Z(t,{received:t.data,code:L.invalid_literal,expected:this._def.value}),ee}return{status:"valid",value:e.data}}get value(){return this._def.value}};Jt.create=(n,e)=>new Jt({value:n,typeName:X.ZodLiteral,...re(e)});function vu(n,e){return new Kt({values:n,typeName:X.ZodEnum,...re(e)})}s(vu,"createZodEnum");var Kt=class n extends oe{static{s(this,"ZodEnum")}constructor(){super(...arguments),cr.set(this,void 0)}_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),r=this._def.values;return Z(t,{expected:pe.joinValues(r),received:t.parsedType,code:L.invalid_type}),ee}if(ao(this,cr,"f")||yu(this,cr,new Set(this._def.values),"f"),!ao(this,cr,"f").has(e.data)){let t=this._getOrReturnCtx(e),r=this._def.values;return Z(t,{received:t.data,code:L.invalid_enum_value,options:r}),ee}return Ne(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return n.create(e,{...this._def,...t})}exclude(e,t=this._def){return n.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}};cr=new WeakMap;Kt.create=vu;var Qt=class extends oe{static{s(this,"ZodNativeEnum")}constructor(){super(...arguments),ur.set(this,void 0)}_parse(e){let t=pe.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==z.string&&r.parsedType!==z.number){let o=pe.objectValues(t);return Z(r,{expected:pe.joinValues(o),received:r.parsedType,code:L.invalid_type}),ee}if(ao(this,ur,"f")||yu(this,ur,new Set(pe.getValidEnumValues(this._def.values)),"f"),!ao(this,ur,"f").has(e.data)){let o=pe.objectValues(t);return Z(r,{received:r.data,code:L.invalid_enum_value,options:o}),ee}return Ne(e.data)}get enum(){return this._def.values}};ur=new WeakMap;Qt.create=(n,e)=>new Qt({values:n,typeName:X.ZodNativeEnum,...re(e)});var At=class extends oe{static{s(this,"ZodPromise")}unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==z.promise&&t.common.async===!1)return Z(t,{code:L.invalid_type,expected:z.promise,received:t.parsedType}),ee;let r=t.parsedType===z.promise?t.data:Promise.resolve(t.data);return Ne(r.then(o=>this._def.type.parseAsync(o,{path:t.path,errorMap:t.common.contextualErrorMap})))}};At.create=(n,e)=>new At({type:n,typeName:X.ZodPromise,...re(e)});var Fe=class extends oe{static{s(this,"ZodEffects")}innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===X.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:r}=this._processInputParams(e),o=this._def.effect||null,i={addIssue:s(a=>{Z(r,a),a.fatal?t.abort():t.dirty()},"addIssue"),get path(){return r.path}};if(i.addIssue=i.addIssue.bind(i),o.type==="preprocess"){let a=o.transform(r.data,i);if(r.common.async)return Promise.resolve(a).then(async c=>{if(t.value==="aborted")return ee;let u=await this._def.schema._parseAsync({data:c,path:r.path,parent:r});return u.status==="aborted"?ee:u.status==="dirty"||t.value==="dirty"?yn(u.value):u});{if(t.value==="aborted")return ee;let c=this._def.schema._parseSync({data:a,path:r.path,parent:r});return c.status==="aborted"?ee:c.status==="dirty"||t.value==="dirty"?yn(c.value):c}}if(o.type==="refinement"){let a=s(c=>{let u=o.refinement(c,i);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c},"executeRefinement");if(r.common.async===!1){let c=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return c.status==="aborted"?ee:(c.status==="dirty"&&t.dirty(),a(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(c=>c.status==="aborted"?ee:(c.status==="dirty"&&t.dirty(),a(c.value).then(()=>({status:t.value,value:c.value}))))}if(o.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!$t(a))return a;let c=o.transform(a.value,i);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>$t(a)?Promise.resolve(o.transform(a.value,i)).then(c=>({status:t.value,value:c})):a);pe.assertNever(o)}};Fe.create=(n,e,t)=>new Fe({schema:n,typeName:X.ZodEffects,effect:e,...re(t)});Fe.createWithPreprocess=(n,e,t)=>new Fe({schema:e,effect:{type:"preprocess",transform:n},typeName:X.ZodEffects,...re(t)});var Ge=class extends oe{static{s(this,"ZodOptional")}_parse(e){return this._getType(e)===z.undefined?Ne(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Ge.create=(n,e)=>new Ge({innerType:n,typeName:X.ZodOptional,...re(e)});var ot=class extends oe{static{s(this,"ZodNullable")}_parse(e){return this._getType(e)===z.null?Ne(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ot.create=(n,e)=>new ot({innerType:n,typeName:X.ZodNullable,...re(e)});var Yt=class extends oe{static{s(this,"ZodDefault")}_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return t.parsedType===z.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Yt.create=(n,e)=>new Yt({innerType:n,typeName:X.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...re(e)});var Xt=class extends oe{static{s(this,"ZodCatch")}_parse(e){let{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},o=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return lr(o)?o.then(i=>({status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new He(r.common.issues)},input:r.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new He(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Xt.create=(n,e)=>new Xt({innerType:n,typeName:X.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...re(e)});var Pn=class extends oe{static{s(this,"ZodNaN")}_parse(e){if(this._getType(e)!==z.nan){let r=this._getOrReturnCtx(e);return Z(r,{code:L.invalid_type,expected:z.nan,received:r.parsedType}),ee}return{status:"valid",value:e.data}}};Pn.create=n=>new Pn({typeName:X.ZodNaN,...re(n)});var hm=Symbol("zod_brand"),dr=class extends oe{static{s(this,"ZodBranded")}_parse(e){let{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}},pr=class n extends oe{static{s(this,"ZodPipeline")}_parse(e){let{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return s(async()=>{let i=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?ee:i.status==="dirty"?(t.dirty(),yn(i.value)):this._def.out._parseAsync({data:i.value,path:r.path,parent:r})},"handleAsync")();{let o=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?ee:o.status==="dirty"?(t.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:r.path,parent:r})}}static create(e,t){return new n({in:e,out:t,typeName:X.ZodPipeline})}},en=class extends oe{static{s(this,"ZodReadonly")}_parse(e){let t=this._def.innerType._parse(e),r=s(o=>($t(o)&&(o.value=Object.freeze(o.value)),o),"freeze");return lr(t)?t.then(o=>r(o)):r(t)}unwrap(){return this._def.innerType}};en.create=(n,e)=>new en({innerType:n,typeName:X.ZodReadonly,...re(e)});function fu(n,e){let t=typeof n=="function"?n(e):typeof n=="string"?{message:n}:n;return typeof t=="string"?{message:t}:t}s(fu,"cleanParams");function xu(n,e={},t){return n?Ot.create().superRefine((r,o)=>{var i,a;let c=n(r);if(c instanceof Promise)return c.then(u=>{var l,d;if(!u){let p=fu(e,r),m=(d=(l=p.fatal)!==null&&l!==void 0?l:t)!==null&&d!==void 0?d:!0;o.addIssue({code:"custom",...p,fatal:m})}});if(!c){let u=fu(e,r),l=(a=(i=u.fatal)!==null&&i!==void 0?i:t)!==null&&a!==void 0?a:!0;o.addIssue({code:"custom",...u,fatal:l})}}):Ot.create()}s(xu,"custom");var ym={object:De.lazycreate},X;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(X||(X={}));var bm=s((n,e={message:`Input not instance of ${n.name}`})=>xu(t=>t instanceof n,e),"instanceOfType"),Pu=Ct.create,Iu=Ut.create,wm=Pn.create,Rm=Ht.create,Eu=Ft.create,vm=jt.create,xm=wn.create,Pm=zt.create,Im=Bt.create,Em=Ot.create,Tm=mt.create,Sm=Je.create,Cm=Rn.create,Om=ft.create,Am=De.create,_m=De.strictCreate,km=Gt.create,Lm=co.create,Nm=Vt.create,Mm=rt.create,Dm=uo.create,Zm=vn.create,qm=xn.create,$m=lo.create,Um=Wt.create,Hm=Jt.create,Fm=Kt.create,jm=Qt.create,zm=At.create,gu=Fe.create,Bm=Ge.create,Gm=ot.create,Vm=Fe.createWithPreprocess,Wm=pr.create,Jm=s(()=>Pu().optional(),"ostring"),Km=s(()=>Iu().optional(),"onumber"),Qm=s(()=>Eu().optional(),"oboolean"),Ym={string:s(n=>Ct.create({...n,coerce:!0}),"string"),number:s(n=>Ut.create({...n,coerce:!0}),"number"),boolean:s(n=>Ft.create({...n,coerce:!0}),"boolean"),bigint:s(n=>Ht.create({...n,coerce:!0}),"bigint"),date:s(n=>jt.create({...n,coerce:!0}),"date")},Xm=ee,x=Object.freeze({__proto__:null,defaultErrorMap:bn,setErrorMap:Vp,getErrorMap:io,makeIssue:so,EMPTY_PATH:Wp,addIssueToContext:Z,ParseStatus:Ae,INVALID:ee,DIRTY:yn,OK:Ne,isAborted:Ki,isDirty:Qi,isValid:$t,isAsync:lr,get util(){return pe},get objectUtil(){return Ji},ZodParsedType:z,getParsedType:pt,ZodType:oe,datetimeRegex:Ru,ZodString:Ct,ZodNumber:Ut,ZodBigInt:Ht,ZodBoolean:Ft,ZodDate:jt,ZodSymbol:wn,ZodUndefined:zt,ZodNull:Bt,ZodAny:Ot,ZodUnknown:mt,ZodNever:Je,ZodVoid:Rn,ZodArray:ft,ZodObject:De,ZodUnion:Gt,ZodDiscriminatedUnion:co,ZodIntersection:Vt,ZodTuple:rt,ZodRecord:uo,ZodMap:vn,ZodSet:xn,ZodFunction:lo,ZodLazy:Wt,ZodLiteral:Jt,ZodEnum:Kt,ZodNativeEnum:Qt,ZodPromise:At,ZodEffects:Fe,ZodTransformer:Fe,ZodOptional:Ge,ZodNullable:ot,ZodDefault:Yt,ZodCatch:Xt,ZodNaN:Pn,BRAND:hm,ZodBranded:dr,ZodPipeline:pr,ZodReadonly:en,custom:xu,Schema:oe,ZodSchema:oe,late:ym,get ZodFirstPartyTypeKind(){return X},coerce:Ym,any:Em,array:Om,bigint:Rm,boolean:Eu,date:vm,discriminatedUnion:Lm,effect:gu,enum:Fm,function:$m,instanceof:bm,intersection:Nm,lazy:Um,literal:Hm,map:Zm,nan:wm,nativeEnum:jm,never:Sm,null:Im,nullable:Gm,number:Iu,object:Am,oboolean:Qm,onumber:Km,optional:Bm,ostring:Jm,pipeline:Wm,preprocess:Vm,promise:zm,record:Dm,set:qm,strictObject:_m,string:Pu,symbol:xm,transformer:gu,tuple:Mm,undefined:Pm,union:km,unknown:Tm,void:Cm,NEVER:Xm,ZodIssueCode:L,quotelessJson:Gp,ZodError:He});var _t="2.0",Tu;(function(n){n[n.ConnectionClosed=-32e3]="ConnectionClosed",n[n.RequestTimeout=-32001]="RequestTimeout",n[n.ParseError=-32700]="ParseError",n[n.InvalidRequest=-32600]="InvalidRequest",n[n.MethodNotFound=-32601]="MethodNotFound",n[n.InvalidParams=-32602]="InvalidParams",n[n.InternalError=-32603]="InternalError"})(Tu||(Tu={}));var In=x.union([x.string(),x.number().int()]);var ef=x.object({jsonrpc:x.literal(_t),id:In,error:x.object({code:x.number().int(),message:x.string(),data:x.optional(x.unknown())})}).strict();var Xi=x.object({_meta:x.optional(x.object({}).passthrough())}).passthrough(),En=x.object({method:x.string(),params:x.optional(Xi)}),Su=x.object({jsonrpc:x.literal(_t)}).merge(En).strict();var tf=x.union([x.string(),x.number().int()]),nf=x.object({progressToken:x.optional(tf)}).passthrough(),gt=x.object({_meta:x.optional(nf)}).passthrough(),ht=x.object({method:x.string(),params:x.optional(gt)}),Cu=x.object({jsonrpc:x.literal(_t),id:In}).merge(ht).strict();var yt=x.object({_meta:x.optional(x.object({}).passthrough())}).passthrough(),ME=yt.strict(),Ou=x.object({jsonrpc:x.literal(_t),id:In,result:yt}).strict();var mr=s(n=>Cu.safeParse(n).success,"isJSONRPCRequest"),Au=s(n=>Su.safeParse(n).success,"isJSONRPCNotification"),po=s(n=>Ou.safeParse(n).success,"isJSONRPCResponse");var es=x.string();var fr=ht.extend({params:gt.extend({cursor:x.optional(es)}).optional()}),gr=yt.extend({nextCursor:x.optional(es)});var _u=x.object({uri:x.string(),mimeType:x.optional(x.string())}).passthrough(),ts=_u.extend({text:x.string()}),ns=_u.extend({blob:x.string().base64()}),rf=x.object({uri:x.string(),name:x.string(),description:x.optional(x.string()),mimeType:x.optional(x.string())}).passthrough(),of=x.object({uriTemplate:x.string(),name:x.string(),description:x.optional(x.string()),mimeType:x.optional(x.string())}).passthrough(),tT=fr.extend({method:x.literal("resources/list")}),nT=gr.extend({resources:x.array(rf)}),rT=fr.extend({method:x.literal("resources/templates/list")}),oT=gr.extend({resourceTemplates:x.array(of)}),iT=ht.extend({method:x.literal("resources/read"),params:gt.extend({uri:x.string()})}),sT=yt.extend({contents:x.array(x.union([ts,ns]))}),aT=En.extend({method:x.literal("notifications/resources/list_changed")}),cT=ht.extend({method:x.literal("resources/subscribe"),params:gt.extend({uri:x.string()})}),uT=ht.extend({method:x.literal("resources/unsubscribe"),params:gt.extend({uri:x.string()})}),lT=En.extend({method:x.literal("notifications/resources/updated"),params:Xi.extend({uri:x.string()})});var ku=x.object({type:x.literal("text"),text:x.string()}).passthrough(),Lu=x.object({type:x.literal("image"),data:x.string().base64(),mimeType:x.string()}).passthrough(),Nu=x.object({type:x.literal("audio"),data:x.string().base64(),mimeType:x.string()}).passthrough(),Mu=x.object({type:x.literal("resource"),resource:x.union([ts,ns])}).passthrough();var sf=x.object({title:x.optional(x.string()),readOnlyHint:x.optional(x.boolean()),destructiveHint:x.optional(x.boolean()),idempotentHint:x.optional(x.boolean()),openWorldHint:x.optional(x.boolean())}).passthrough(),af=x.object({name:x.string(),description:x.optional(x.string()),inputSchema:x.object({type:x.literal("object"),properties:x.optional(x.object({}).passthrough())}).passthrough(),annotations:x.optional(sf)}).passthrough(),vT=fr.extend({method:x.literal("tools/list")}),xT=gr.extend({tools:x.array(af)}),cf=yt.extend({content:x.array(x.union([ku,Lu,Nu,Mu])),isError:x.boolean().default(!1).optional()}),PT=cf.or(yt.extend({toolResult:x.unknown()})),Du=ht.extend({method:x.literal("tools/call"),params:gt.extend({name:x.string(),arguments:x.optional(x.record(x.unknown()))})}),IT=En.extend({method:x.literal("notifications/tools/list_changed")});var Zu="2025-03-26";var mo=class{static{s(this,"MCPServer")}capabilities;tools=new Map;name;version;instructions;constructor(e){this.name=e.name||"MCP Server",this.version=e.version||"1.0.0",this.instructions=e.instructions||void 0,this.capabilities={tools:{supported:!0,available:[]},...e.capabilities}}withTransport(e){e.onMessage(async t=>{try{if(mr(t)){let r=await this.handleRequest(t);if(r)return await e.send(r),r}else{if(Au(t))return await this.handleNotification(t),null;if(po(t))return console.log("Received response:",t),null}}catch(r){if(console.error("Error processing message:",r),mr(t)){let o={jsonrpc:"2.0",id:t.id,error:{code:-32603,message:r instanceof Error?r.message:"Internal error"}};return await e.send(o),o}}return null})}getTool(e){throw new Error("Method not implemented.")}getTools(){throw new Error("Method not implemented.")}getCapabilities(){return{...this.capabilities}}addTool(e){let{name:t,validator:r,handler:o,description:i=`Execute the ${t} tool`}=e,c={tool:{name:t,description:i,inputSchema:r.jsonSchema},validator:r,handler:o};this.tools.set(t,c),this.updateAvailableTools()}removeTool(e){let t=this.tools.delete(e);return t&&this.updateAvailableTools(),t}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(t){return console.error("Error handling request:",t),{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:t instanceof Error?t.message:"Internal error"}}}}async handleNotification(e){console.log("received notification",e.method)}handlePing(e){return{jsonrpc:"2.0",id:e.id,result:{}}}handleInitialize(e){let t={protocolVersion:Zu,capabilities:this.getCapabilities(),serverInfo:{name:this.name,version:this.version},...this.instructions?{instructions:this.instructions}:{}};return{jsonrpc:"2.0",id:e.id,result:t}}async handleToolListRequest(e){let r={tools:Array.from(this.tools.entries()).map(([o,i])=>i.tool)};return{jsonrpc:"2.0",id:e.id,result:r}}async handleToolCallRequest(e){let t=Du.safeParse(e);if(!t.success)return console.log("could not validate tool call with calltoolrequestschema"),{jsonrpc:"2.0",id:e.id,error:{code:-32600,message:`Invalid request ${t.error}`}};let r=t.data,o=r.params.name,i=this.tools.get(o);if(!i)return{jsonrpc:"2.0",id:e.id,error:{code:-32601,message:`Tool "${o}" not found`}};let a=r.params.arguments??{},c=i.validator.parse(a);if(!c.success)return{jsonrpc:"2.0",id:e.id,error:{code:-32602,message:"Invalid params",data:c.error}};try{let u=c.data,l=await i.handler(u);return{jsonrpc:"2.0",id:e.id,result:l}}catch(u){return console.error(`Error executing tool "${o}":`,u),{jsonrpc:"2.0",id:e.id,error:{code:-32603,message:u instanceof Error?u.message:"Tool execution error"}}}}updateAvailableTools(){this.capabilities.tools&&(this.capabilities.tools.available=Array.from(this.tools.keys()))}};var fo=class{static{s(this,"HTTPStreamableTransport")}messageHandler=null;closeCallback=null;options;connected=!1;enableStreaming=!1;sessions=new Map;streams=new Map;constructor(e={},t=!1){this.options={timeout:30*60*1e3,enableSessions:!1,...e},t&&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(po(e)){for(let[t,r]of this.sessions.entries())for(let[o,i]of r.streams.entries())if(i.pendingRequests.has(e.id)){await this.sendToStream(i,e),i.pendingRequests.delete(e.id),i.pendingRequests.size===0&&await this.closeStream(t,o);return}}else for(let t of this.sessions.values()){let r=[...t.streams.values()][0];r&&(await this.sendToStream(r,e),mr(e)&&r.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[t,r]of e.streams.entries())try{await r.writer.close()}catch(o){console.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 t=e.method.toUpperCase();try{this.validateOrigin(e);let r=e.headers.get("Mcp-Session-Id"),o;if(r&&(o=this.sessions.get(r),!o&&t!=="DELETE"))return new Response(null,{status:404});switch(t){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(r){console.error("Error handling request:",r);let o=400,i={jsonrpc:"2.0",error:{code:-32603,message:r||"Server error"},id:null};return new Response(JSON.stringify(i),{status:o,headers:{"Content-Type":"application/json"}})}}async handlePostRequest(e,t){let r=e.headers.get("Accept")||"";if(!r.includes("application/json")&&!r.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 i=Array.isArray(o)?o:[o],a=i.some(u=>this.isRequest(u)),c=t;if(this.options.enableSessions&&!c&&i.some(u=>this.isRequest(u)&&u.method==="initialize")){let u=this.generateFallbackUUID();c=this.createSession(u)}try{if(!a){for(let m of i)await this.messageHandler?.(m);return new Response(null,{status:202,headers:c?{"Mcp-Session-Id":c.id}:void 0})}if(!this.enableStreaming){let m=[];for(let b of i)if(this.isRequest(b)){let P=await this.messageHandler?.(b);P&&m.push(P)}else await this.messageHandler?.(b);let h=m.length===1?m[0]:m,w={"Content-Type":"application/json"};return c&&(w["Mcp-Session-Id"]=c.id),new Response(JSON.stringify(h),{status:200,headers:w})}let{stream:u,streamId:l}=this.createStream(c),d=[];for(let m of i)if(this.isRequest(m)){this.streams.get(l)?.pendingRequests.add(m.id);let h=this.messageHandler?.(m);d.push(h)}else await this.messageHandler?.(m);let p={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};return c&&(p["Mcp-Session-Id"]=c.id),new Response(u.readable,{headers:p})}catch(u){return new Response(JSON.stringify({jsonrpc:"2.0",error:{code:-32603,message:u||"Internal error"},id:null}),{status:500,headers:{"Content-Type":"application/json"}})}}async handleGetRequest(e,t){if(!(e.headers.get("Accept")||"").includes("text/event-stream"))return new Response(null,{status:406,headers:{"Content-Type":"application/json"}});if(this.options.enableSessions&&!t)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:i}=this.createStream(t),a=e.headers.get("Last-Event-ID");a&&t&&await this.replayMessages(t,i,a);let c={"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"};return t&&(c["Mcp-Session-Id"]=t.id),new Response(o.readable,{headers:c})}async handleDeleteRequest(e,t){if(!t)return new Response(null,{status:400});if(this.options.enableSessions&&t){let r=this.sessions.get(t);if(r){for(let[o,i]of r.streams.entries())await this.closeStream(t,o);return this.sessions.delete(t),new Response(null,{status:204})}}return new Response(null,{status:404})}async sendToStream(e,t){try{let r=String(++e.eventCounter),o=JSON.stringify(t);e.messages.push(t),e.messages.length>100&&e.messages.shift();let i=`id: ${r}
|
|
70
70
|
data: ${o}
|
|
71
71
|
|
|
72
72
|
`;await e.writer.write(new TextEncoder().encode(i))}catch(r){console.warn("Error sending to stream:",r)}}async closeStream(e,t){let r=this.sessions.get(e);if(!r)return;let o=r.streams.get(t);if(o){try{await o.writer.close()}catch(i){console.warn("Error closing stream:",i)}r.streams.delete(t),this.streams.delete(t)}}createSession(e){let t={id:e,createdAt:Date.now(),lastActivity:Date.now(),streams:new Map};return this.sessions.set(e,t),t}createStream(e){let t=new TransformStream,r=t.writable.getWriter(),o=crypto.randomUUID?.()||this.generateFallbackUUID(),i={id:o,writer:r,eventCounter:0,messages:[],pendingRequests:new Set};return this.streams.set(o,i),e&&(e.streams.set(o,i),e.lastActivity=Date.now()),{stream:t,streamId:o}}async replayMessages(e,t,r){for(let o of e.streams.values()){if(o.id===t)continue;let i=Number.parseInt(r,10);if(Number.isNaN(i))continue;let a=o.messages.slice(i),c=this.streams.get(t);if(c&&a.length>0)for(let u of a)await this.sendToStream(c,u)}}startSessionCleanup(){setInterval(()=>{let e=Date.now();for(let[t,r]of this.sessions.entries()){let o=this.options.timeout??6e4;if(e-r.lastActivity>o){for(let[i,a]of r.streams.entries()){try{a.writer.close().catch(c=>console.warn("Error closing stream:",c))}catch(c){console.warn("Error closing stream:",c)}this.streams.delete(i)}this.sessions.delete(t)}}},6e4)}async extractJSONRPC(e){try{let r=await e.clone().text();if(!r)throw new Error("Empty request body");return JSON.parse(r)}catch(t){throw new Error(`Failed to parse JSON-RPC message: ${t}`)}}validateOrigin(e){let t=e.headers.get("Origin");if(t&&!this.isValidOrigin(t))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 t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}};async function uf(n,e){g("handler.mcp-server");let t=e.route.handler.options,r=new mo({name:t?.name??"Zuplo MCP Server",version:t?.version??"0.0.0"}),o=new fo;return await o.connect(),r.withTransport(o),await o.handleRequest(n)}s(uf,"mcpServerHandler");var rs=class extends Re{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new os(this.options)}},os=class{static{s(this,"DynaTraceTransport")}constructor(e){g("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{}}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o=Object.assign({timestamp:new Date().toISOString(),message:$e(r),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"custom.atomicCounter":e.vectorClock,"custom.environment":this.#n,"custom.environmentStage":this.#o,"custom.environmentType":this.#r,"custom.loggingId":e.loggingId,"custom.rayId":e.rayId===null?void 0:e.rayId},this.#i);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=s(async e=>{if(e.length!==0)try{let t=await j.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}});t.ok||await se({level:"error",messages:[`Failed to send logs to Dynatrace: ${t.status} - ${t.statusText}`]},t)}catch{await se({level:"error",messages:["Failed to connect to Dynatrace logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ie("dyna-trace-log-transport",10,this.#s)};var is=class extends Re{constructor(t){super();this.options=t}static{s(this,"NewRelicLoggingPlugin")}getTransport(){return new ss(this.options)}},ss=class{static{s(this,"NewRelicTransport")}constructor(e){g("logging.newrelic"),this.#e=e.url??"https://log-api.newrelic.com/log/v1",this.#t=e.apiKey,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.service??"Zuplo"}#e;#t;#n;#r;#o;#i;#s;log(e,t){e.messages.forEach(r=>{let o=Object.assign({message:$e(r),level:e.level,timestamp:Date.now(),service:this.#s,request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource},this.#i);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=s(async e=>{if(e.length!==0)try{let t=await j.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/json","Api-Key":this.#t}});t.ok||await se({level:"error",messages:[`Failed to send logs to New Relic: ${t.status} - ${t.statusText}`]},t)}catch{await se({level:"error",messages:["Failed to connect to New Relic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ie("new-relic-log-transport",10,this.#a)};var as=class extends Re{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new us(this.options)}},cs=class{static{s(this,"LokiStream")}constructor(e,t,r,o,i,a){this.level=e,this.environment=t,this.environmentType=r,this.environmentStage=o,this.requestId=a,this.job=i}job;level;environment;environmentType;environmentStage;requestId;equals=s(e=>this.level===e.level&&this.requestId===e.requestId,"equals")};function lf(n,e){return btoa(`${n}:${e}`)}s(lf,"createBasicDigest");var us=class{static{s(this,"LokiTransport")}constructor(e){g("logging.loki"),this.#n=e.url,this.#r=lf(e.username,e.password),this.#i=y.instance.loggingEnvironmentType,this.#s=y.instance.loggingEnvironmentStage,this.#o=y.instance.deploymentName,this.#e=e.version??1,this.#t=e.job??"zuplo",this.#a=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;#a;log(e,t){let r=new cs(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let i=Object.assign({stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:$e(o),nanoSecondEpoch:`${e.timestamp.getTime()}000000`},this.#a);this.batcher.enqueue(i)}),t.waitUntil(this.batcher.waitUntilFlushed())}#c=s(e=>{let t={streams:[]};return e.forEach(r=>{let o=t.streams.find(i=>i.stream.equals(r.stream));o||(o={stream:r.stream,values:[]},t.streams.push(o)),o.values.push(this.#e>1?[r.nanoSecondEpoch,r.message,{requestId:r.requestId,rayId:r.rayId,atomicCounter:JSON.stringify(r.atomicCounter)}]:[r.nanoSecondEpoch,r.message])}),t},"#convertToLokiStreamsBatch");#u=s(async e=>{if(e.length===0)return;let t=this.#c(e);try{let r=await j.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}});r.ok||await se({level:"error",messages:[`Failed to send logs to Loki: ${r.status} - ${r.statusText}`]},r)}catch{await se({level:"error",messages:["Failed to connect to Loki logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ie("loki-log-transport",10,this.#u)};var ls=class extends Re{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new ds(this.options)}},ds=class{static{s(this,"SumoLogicTransport")}constructor(e){g("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=y.instance.loggingEnvironmentType,this.#r=y.instance.loggingEnvironmentStage,this.#t=y.instance.deploymentName,this.#s=e.fields??{}}#e;#t;#n;#r;#o;#i;#s;log(e,t){e.messages.forEach(r=>{let o=Object.assign({timestamp:new Date().toISOString(),message:$e(r),severity:e.level,source:e.logSource,requestId:e.requestId,environment:this.#t,environmentType:this.#n,environmentStage:this.#r,rayId:e.rayId===null?void 0:e.rayId},this.#s);this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=s(async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
|
|
73
73
|
`),r=new Headers({"content-type":"application/json; charset=utf-8"});this.#i&&r.set("X-Sumo-Name",this.#i),this.#o&&r.set("X-Sumo-Category",this.#o);try{let o=await j.fetch(this.#e,{method:"POST",body:t,headers:r});o.ok||await se({level:"error",messages:[`Failed to send logs to Sumologic: ${o.status} - ${o.statusText}`]},o)}catch{await se({level:"error",messages:["Failed to connect to Sumologic logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ie("sumo-logic-log-transport",10,this.#a)};var df="d3a5b78f823648f5b1df4fe269d41172",ps=class extends Re{constructor(t){super();this.options=t}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new ms(this.options)}},ms=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){g("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??df}`)}catch{throw new f(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.onMessageSending,this.#t=e.textReplacements,e.fields&&(this.#s=Object.entries(e.fields).map(([r,o])=>({name:r,content:o})))}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=this.buildEntry(e,t);this.batcher.enqueue(r),t.waitUntil(this.batcher.waitUntilFlushed())}buildEntry(e,t){let r=Fc(e.messages);this.#t?.forEach(i=>{r=r.replaceAll(i[0],i[1])});let o={timestamp:Date.now(),text:r,fields:[{name:"severity",content:e.level.toUpperCase()},{name:"request_id",content:e.requestId},{name:"environment_type",content:this.#r},{name:"environment_stage",content:this.#o},{name:"log_source",content:e.logSource},{name:"atomic_counter",content:e.vectorClock}]};return e.rayId&&o.fields.push({name:"request_ray_id",content:e.rayId}),this.#n&&o.fields.push({name:"environment",content:this.#n}),this.#s&&o.fields.push(...this.#s),t.custom&&Object.entries(t.custom).forEach(([i,a])=>{let c=Ci(a);c&&o.fields.push({name:i,content:c})}),this.#i&&(o=this.#i(o)),o}#a=s(async e=>{if(e.length!==0)try{let t=await j.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});t.ok||await se({level:"error",messages:[`Failed to send logs to Log Insight: ${t.status} - ${t.statusText}`]},t)}catch{await se({level:"error",messages:["Failed to connect to Log Insight logging service. Check that the URL is correct."]})}},"#dispatchFunction");batcher=new ie("vmware-log-insights-log-transport",10,this.#a)};var fs=class extends Re{constructor(t){super();this.options=t}static{s(this,"AWSLoggingPlugin")}getTransport(){return new gs(this.options)}},gs=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;environmentStage;logGroupName;logStreamName;region;fields;batcher=new ie("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});try{let r=await this.awsClient.fetch(`https://logs.${this.region}.amazonaws.com`,{headers:{"Content-Type":"application/x-amz-json-1.1","x-amz-Target":"Logs_20140328.PutLogEvents"},body:t,aws:{accessKeyId:this.awsClient.accessKeyId,secretAccessKey:this.awsClient.secretAccessKey,service:this.awsClient.service,region:this.awsClient.region}});r.ok||await se({level:"error",messages:[`Failed to send logs to AWS: ${r.status} - ${r.statusText}`]},r)}catch{await se({level:"error",messages:["Failed to connect to AWS logging service. Check that the URL is correct."]})}});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:i,fields:a}){g("logging.aws"),this.awsClient=new mn({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=t,this.region=i,this.environmentType=y.instance.loggingEnvironmentType,this.environmentStage=y.instance.loggingEnvironmentStage,this.environment=y.instance.deploymentName,this.fields=a??{}}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify(Object.assign({data:$e(r),severity:e.level,source:e.logSource,environment:this.environment,atomicCounter:e.vectorClock,requestId:e.requestId,environmentType:this.environmentType,environmentStage:this.environmentStage,rayId:e.rayId===null?void 0:e.rayId},this.fields))};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var hs=class extends Re{constructor(t){super();this.options=t}static{s(this,"SplunkLoggingPlugin")}getTransport(){return new ys(this.options)}},ys=class{static{s(this,"SplunkTransport")}constructor(e){g("logging.splunk"),this.#e=e.url,this.#t=e.token,this.#r=y.instance.loggingEnvironmentType,this.#o=y.instance.loggingEnvironmentStage,this.#n=y.instance.deploymentName,this.#i=e.fields??{},this.#s=e.index??"main",this.#a=e.sourcetype??"json",this.#c=e.host??"zuplo-api",this.#u=e.channel}#e;#t;#n;#r;#o;#i;#s;#a;#c;#u;log(e,t){e.messages.forEach(r=>{let i={event:{message:$e(r),level:e.level,timestamp:new Date().toISOString(),request_id:e.requestId,atomic_counter:e.vectorClock,environment:this.#n,environment_stage:this.#o,environment_type:this.#r,logging_id:e.loggingId,ray_id:e.rayId===null?void 0:e.rayId,log_source:e.logSource,...this.#i},sourcetype:this.#a,host:this.#c,index:this.#s,time:Math.floor(Date.now()/1e3)};this.batcher.enqueue(i)}),t.waitUntil(this.batcher.waitUntilFlushed())}#l=s(async e=>{if(e.length!==0)try{for(let t of e){let r={"Content-Type":"application/json",Authorization:`Splunk ${this.#t}`};this.#u&&(r["X-Splunk-Request-Channel"]=this.#u);let o=await j.fetch(this.#e,{method:"POST",body:JSON.stringify(t),headers:r});if(!o.ok){let i=await o.text();await se({level:"error",messages:[`Failed to send logs to Splunk: ${o.status} - ${o.statusText}`,`Response: ${i}`]},o)}}}catch(t){await se({level:"error",messages:["Failed to connect to Splunk logging service. Check that the URL is correct.",`Error: ${t instanceof Error?t.message:String(t)}`]})}},"#dispatchFunction");batcher=new ie("splunk-log-transport",10,this.#l)};var bs=new WeakMap,pf={tags:[]},ws=class extends tt{constructor(t){super();this.options=t;g("metrics.datadog")}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new Rs(this.options)}static setContext(t,r){let o=bs.get(t);o||(o=pf);let i=Object.assign({...o},r);bs.set(t,i)}},Rs=class{static{s(this,"DataDogMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://api.datadoghq.com/api/v2/series",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.tags??[]}pushMetrics(e,t){this.#i===void 0&&(this.#i=new ie("data-dog-metrics-transport",10,this.dispatchFunction,ne.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(bs.get(t)?.tags??[]);if(this.#o.country&&o.push(`country:${e.country}`),this.#o.httpMethod&&o.push(`httpMethod:${e.method}`),this.#o.statusCode&&o.push(`statusCode:${e.statusCode}`),this.#o.path){let i=e.systemRouteName||e.routePath;o.push(`path:${i}`)}this.#n.latency&&this.#i.enqueue({metric:"zuplo.request.latency",type:3,points:[{timestamp:r,value:e.durationMs}],tags:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({metric:"zuplo.request.content_length",type:3,points:[{timestamp:r,value:e.requestContentLength}],tags:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({metric:"zuplo.response.content_length",type:3,points:[{timestamp:r,value:e.responseContentLength}],tags:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let t=JSON.stringify({series:e}),r=await j.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});r.ok||await se({level:"error",messages:["Failed to send metrics to DataDog."]},r)}catch{await se({level:"error",messages:["Failed to connect to DataDog metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var vs=new WeakMap,mf={dimensions:[]},xs=class extends tt{constructor(t){super();this.options=t;g("metrics.dynatrace")}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new Ps(this.options)}static setContext(t,r){let o=vs.get(t);o||(o=mf);let i=Object.assign({...o},r);vs.set(t,i)}},Ps=class{static{s(this,"DynaTraceMetricsTransport")}apiToken;#e;#t;dimensions;#n;#r=void 0;constructor(e){this.apiToken=e.apiToken,this.#e=e.url,this.#t=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#n=e.include??{},this.dimensions=e.dimensions??[]}pushMetrics(e,t){this.#r===void 0&&(this.#r=new ie("dynatrace-metrics-transport",10,this.dispatchFunction,ne.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(vs.get(t)?.dimensions??[]);if(this.#n.country&&o.push(`country="${e.country}"`),this.#n.httpMethod&&o.push(`http_method="${e.method}"`),this.#n.statusCode&&o.push(`status_code="${e.statusCode}"`),this.#n.path){let a=e.systemRouteName||e.routePath;o.push(`path="${a}"`)}let i=o.join(",");this.#t.latency&&this.#r.enqueue(`zuplo.request.latency,${i} ${e.durationMs} ${r}`),this.#t.requestContentLength&&e.requestContentLength&&this.#r.enqueue(`zuplo.request.content_length,${i} ${e.requestContentLength} ${r}`),this.#t.responseContentLength&&e.responseContentLength&&this.#r.enqueue(`zuplo.response.content_length,${i} ${e.responseContentLength} ${r}`),t.waitUntil(this.#r.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let t=e.join(`
|
|
74
74
|
`),r=await j.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});r.ok||await se({level:"error",messages:["Failed to send metrics to Dynatrace."]},r)}catch{await se({level:"error",messages:["Failed to connect to Dynatrace metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Is=new WeakMap,ff={attributes:{}},Es=class extends tt{constructor(t){super();this.options=t;g("metrics.newrelic")}static{s(this,"NewRelicMetricsPlugin")}getTransport(){return new Ts(this.options)}static setContext(t,r){let o=Is.get(t);o||(o=ff);let i=Object.assign({...o},r);Is.set(t,i)}},Ts=class{static{s(this,"NewRelicMetricsTransport")}#e;#t;#n;#r;#o;#i=void 0;constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://metric-api.newrelic.com/metric/v1",this.#n=Object.assign({latency:!0,requestContentLength:!0,responseContentLength:!0},e.metrics),this.#o=e.include??{},this.#r=e.attributes??{service:"zuplo"}}pushMetrics(e,t){this.#i===void 0&&(this.#i=new ie("new-relic-metrics-transport",10,this.dispatchFunction,ne.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o={...this.#r,...Is.get(t)?.attributes};if(this.#o.country&&(o.country=e.country),this.#o.httpMethod&&(o.httpMethod=e.method),this.#o.statusCode&&(o.statusCode=e.statusCode.toString()),this.#o.path){let i=e.systemRouteName||e.routePath;o.path=i}this.#n.latency&&this.#i.enqueue({name:"zuplo.request.latency",type:"gauge",value:e.durationMs,timestamp:r,attributes:o}),this.#n.requestContentLength&&e.requestContentLength&&this.#i.enqueue({name:"zuplo.request.content_length",type:"gauge",value:e.requestContentLength,timestamp:r,attributes:o}),this.#n.responseContentLength&&e.responseContentLength&&this.#i.enqueue({name:"zuplo.response.content_length",type:"gauge",value:e.responseContentLength,timestamp:r,attributes:o}),t.waitUntil(this.#i.waitUntilFlushed())}dispatchFunction=s(async e=>{if(e.length!==0)try{let t=JSON.stringify([{metrics:e}]),r=await j.fetch(this.#t,{method:"POST",body:t,headers:{"Content-Type":"application/json","Api-Key":this.#e}});r.ok||await se({level:"error",messages:[`Failed to send metrics to New Relic. Status: ${r.status} ${r.statusText}`]},r)}catch{await se({level:"error",messages:["Failed to connect to New Relic metrics service. Check that the URL is correct."]})}},"dispatchFunction")};var Ss=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,g("audit-logs.datastax")}#e;writeLogBatch=s(async e=>{await Promise.allSettled(e.map(async t=>{await j.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))},"writeLogBatch")};var Cs=class extends Ee{static{s(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,g("audit-logs")}#e;#t;async initialize(e){new Os(e,this.#e,this.#t)}},qu=s(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),gf={requestFilter:s(async()=>!0,"requestFilter"),include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},Os=class{static{s(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...gf};r?.requestFilter&&(o.requestFilter=r.requestFilter),r?.include?.request&&Object.assign(o,r.include.request),r?.include?.response&&Object.assign(o,r.include.response),this.#e=o,e.addRequestHook(this.#i),this.#n=new ie("audit-log",10,this.#r)}#e;#t;#n;#r=s(async e=>{await this.#t.writeLogBatch(e)},"#dispatch");#o=s(async(e,t,r,o,i,a)=>{try{let c={timestamp:o,durationMs:i,routePath:r.route.path,requestId:r.requestId,userSub:a,request:{url:t.url,method:t.method,headers:this.#e.include?.request?.headers?qu(t.headers):void 0,body:this.#e.include?.request?.body?await t.text():void 0},response:{status:e.status,statusText:e.statusText,headers:this.#e.include?.response?.headers?qu(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(c),r.waitUntil(this.#n.waitUntilFlushed())}catch(c){r.log.error(c)}},"#asyncPrepLogs");#i=s(async(e,t)=>{try{if(!await this.#e.requestFilter(e,t))return e;let o=new Date,i=Date.now(),a=e.clone();return t.addResponseSendingFinalHook(async(c,u)=>{let l=Date.now(),d=c.clone(),p=this.#o(d,a,t,o,l-i,u.user?.sub).catch(m=>{t.log.error(m)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}},"#auditHook")};var As={None:0,JsonEscape:1},hr=class{constructor(e,t={}){this.stream=e;this.options=t;this.placeholder=`__STREAM_TOKEN_${crypto.randomUUID()}__`}static{s(this,"StreamToken")}placeholder;getRawStream(){return this.stream}getOptions(){return this.options}getSafeToken(){return this.placeholder}async getContent(){if(!this.stream)return this.options.useEmptyStringIfNull?"":null;let e=this.stream.getReader(),t=[];try{for(;;){let{done:c,value:u}=await e.read();if(c)break;t.push(u)}}finally{e.releaseLock()}let r=t.reduce((c,u)=>c+u.length,0),o=new Uint8Array(r),i=0;for(let c of t)o.set(c,i),i+=c.length;let a=new TextDecoder().decode(o);return this.options.base64Encode&&(a=btoa(a)),a}},go=class{static{s(this,"StreamBuilder")}template;tokens;flags;constructor(e){this.template=e.template,this.tokens=e.tokens,this.flags=e.flags}escapeJsonString(e){return e.replace(/[\\\"\n\r\t\f\b]/g,t=>{switch(t){case"\\":return"\\\\";case'"':return'\\"';case`
|
|
75
|
-
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return t}})}async toString(){let t=this.getStream().getReader(),r=new TextDecoder,o="";for(;;){let{done:i,value:a}=await t.read();if(i)break;o+=r.decode(a,{stream:!0})}return o+=r.decode(),o}getStream(){let e=this.template,t=this.flags,r=new TextEncoder,o=new Map;for(let m of this.tokens)o.set(m.getSafeToken(),m);let i=/"(__STREAM_TOKEN_[^"]+__)"|(__STREAM_TOKEN_[^"]+__)/g,a=[],c=0,u;for(;(u=i.exec(e))!==null;){if(u.index>c&&a.push({type:"literal",value:e.substring(c,u.index)}),u[1]){let m=o.get(u[1]);m?a.push({type:"token",token:m,isQuoted:!0}):a.push({type:"literal",value:u[0]})}else if(u[2]){let m=o.get(u[2]);m?a.push({type:"token",token:m,isQuoted:!1}):a.push({type:"literal",value:u[0]})}c=i.lastIndex}c<e.length&&a.push({type:"literal",value:e.substring(c)});function l(){let m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h=new Uint8Array(0);return new TransformStream({transform(
|
|
76
|
-
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return b}});h.enqueue(
|
|
75
|
+
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return t}})}async toString(){let t=this.getStream().getReader(),r=new TextDecoder,o="";for(;;){let{done:i,value:a}=await t.read();if(i)break;o+=r.decode(a,{stream:!0})}return o+=r.decode(),o}getStream(){let e=this.template,t=this.flags,r=new TextEncoder,o=new Map;for(let m of this.tokens)o.set(m.getSafeToken(),m);let i=/"(__STREAM_TOKEN_[^"]+__)"|(__STREAM_TOKEN_[^"]+__)/g,a=[],c=0,u;for(;(u=i.exec(e))!==null;){if(u.index>c&&a.push({type:"literal",value:e.substring(c,u.index)}),u[1]){let m=o.get(u[1]);m?a.push({type:"token",token:m,isQuoted:!0}):a.push({type:"literal",value:u[0]})}else if(u[2]){let m=o.get(u[2]);m?a.push({type:"token",token:m,isQuoted:!1}):a.push({type:"literal",value:u[0]})}c=i.lastIndex}c<e.length&&a.push({type:"literal",value:e.substring(c)});function l(){let m="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",h=new Uint8Array(0);return new TransformStream({transform(w,b){let P=new Uint8Array(h.length+w.length);P.set(h),P.set(w,h.length);let N=P.length%3,A=P.length-N;if(A>0){let B=P.subarray(0,A),$="";for(let G=0;G<B.length;G+=3){let O=B[G],F=B[G+1],Y=B[G+2],V=O<<16|F<<8|Y;$+=m[V>>18&63],$+=m[V>>12&63],$+=m[V>>6&63],$+=m[V&63]}b.enqueue($)}h=P.subarray(P.length-N)},flush(w){if(h.length>0){let b=h[0],P=h.length>1?h[1]:0,N=b<<16|P<<8,A="";A+=m[N>>18&63],A+=m[N>>12&63],A+=h.length===2?m[N>>6&63]:"=",A+="=",w.enqueue(A)}}})}s(l,"createBase64EncodeTransformStream");function d(){return new TransformStream({transform(m,h){let w=m.replace(/[\\\"\n\r\t\f\b]/g,b=>{switch(b){case"\\":return"\\\\";case'"':return'\\"';case`
|
|
76
|
+
`:return"\\n";case"\r":return"\\r";case" ":return"\\t";case"\f":return"\\f";case"\b":return"\\b";default:return b}});h.enqueue(w)}})}s(d,"createJsonEscapeTransformStream");async function*p(){for(let m of a)if(m.type==="literal")yield r.encode(m.value);else{let h=m.token,w=h.getRawStream();if(!w){m.isQuoted?yield r.encode(h.getOptions().useEmptyStringIfNull?'""':"null"):yield r.encode(h.getOptions().useEmptyStringIfNull?"":"null");continue}let b;h.getOptions().base64Encode?b=w.pipeThrough(l()):b=w.pipeThrough(new TextDecoderStream),!h.getOptions().base64Encode&&t&As.JsonEscape&&(b=b.pipeThrough(d())),m.isQuoted&&(yield r.encode('"'));let P="";try{let N=b.getReader(),A=await N.read();if(A.done)throw new Error("Token stream already exhausted.");for(P+=A.value;;){let{done:B,value:$}=await N.read();if(B)break;P+=$}}catch(N){P=`Error: reading stream failed - ${N instanceof Error?N.message:String(N)}`}yield r.encode(P),m.isQuoted&&(yield r.encode('"'))}}return s(p,"generateChunks"),new ReadableStream({async start(m){for await(let h of p())m.enqueue(h);m.close()}})}};function $u(n){try{let e=n.split(".")[1],t=Buffer.from(e,"base64").toString("utf8");return JSON.parse(t)}catch{return null}}s($u,"decodeJWT");function Uu(n,e,t){if(n.IP&&t&&n.IP[t])return{blocked:!0,id:n.IP[t],source:`IP/${t}`};if(n.Header)for(let[r,o]of Object.entries(n.Header)){let i=e.headers.get(r);if(i){if(o.RAW&&o.RAW[i])return{blocked:!0,id:o.RAW[i],source:`Header/${r}/RAW/${i}`};if(o.JWT){let a=i;if(r.toLowerCase()==="authorization"){let u=i.split(" ");u.length===2&&u[0].toLowerCase()==="bearer"&&(a=u[1])}let c=$u(a);if(c){for(let[u,l]of Object.entries(o.JWT))if(c[u]&&l[c[u]])return{blocked:!0,id:l[c[u]],source:`Header/${r}/JWT/${u}/${c[u]}`}}}if(r.toLowerCase()==="cookie"&&o.COOKIE){let a=i.split(";").reduce((c,u)=>{let[l,d]=u.trim().split("=");return c[l]=d,c},{});for(let[c,u]of Object.entries(o.COOKIE))if(a[c]&&u[a[c]])return{blocked:!0,id:u[a[c]],source:`Header/Cookie/${c}/${a[c]}`}}}}if(n.Query){let r=new URL(e.url);for(let[o,i]of Object.entries(n.Query)){let a=r.searchParams.get(o);if(a){if(i.RAW&&i.RAW[a])return{blocked:!0,id:i.RAW[a],source:`Query/${o}/RAW/${a}`};if(i.JWT){let c=$u(a);if(c){for(let[u,l]of Object.entries(i.JWT))if(c[u]&&l[c[u]])return{blocked:!0,id:l[c[u]],source:`Query/${o}/JWT/${u}/${c[u]}`}}}}}}return{blocked:!1}}s(Uu,"checkRequest");var hf=1048576,yf=1e3;function Hu(n,e){if(!n.body||n.body===null)return!1;let t=n.headers.get("content-length");return!(Number(t)>hf||(n.headers.get("content-type")??"").includes("stream")||e!=null&&e===101)}s(Hu,"shouldGatherBody");var bf="unused",_s={type:63,version:"3.0.1"},ks,wf="plugin.akamai-api-security-plugin",Ls=class extends Ee{static{s(this,"AkamaiApiSecurityPlugin")}constructor(e){super(),this.#r=e,this.#n=xf(e.hostname),g(wf)}async initialize(e){e.addRequestHook(async(t,r)=>{if(ks=r,this.#r.enableProtection===!0)try{let a=await this.#t.get(bf);this.#r.debug&&r.log.debug("AkamaiApiSecurityPlugin: Loaded ProtectionResponse",a);let c=Uu(a,t);if(c.blocked===!0)return r.log.debug(`AkamaiApiSecurityPlugin: Request Blocked by rule '${c.source}':'${c.id}'`),T.forbidden(t,r,{detail:"Access to this resource has been forbidden"})}catch(a){r.log.error(`AkamaiApiSecurityPlugin: Error loading ProtectionResponse '${a.message}'`)}if(this.#r.shouldLog&&!await this.#r.shouldLog(t,r))return t;let o=Date.now(),i=null;return Hu(t)&&(i=t.clone().body),r.addResponseSendingFinalHook(async(a,c,u)=>{let l=null;Hu(a)&&(l=a.clone().body);let d=this.#o(i,l,c,a,u,o);u.waitUntil(d)}),t})}#e=s(async()=>{let e=await fetch(`${this.#n}/integrations-adapter/get-prevention-rules?source-index=${this.#r.index}&source-key=${this.#r.key}&source-type=${_s.type}`);if(e.status!==200)throw new Error(`Unexpected response from protection endpoint ${e.status}: ${await e.text()}`);let t=await e.text();try{return JSON.parse(t)}catch(r){throw new Error(`Error parsing response from protection endpoint '${r}' in '${t}'`)}},"#protectionFetch");#t=new yr(this.#e,{ttlSeconds:60,loaderTimeoutSeconds:60});#n;#r;#o=s(async(e,t,r,o,i,a)=>{let c=new hr(e,{base64Encode:!0,useEmptyStringIfNull:!0}),u=new hr(t,{base64Encode:!0,useEmptyStringIfNull:!0}),l=await this.#i(o,r,u,c,i,a),p=new go({template:JSON.stringify(l),tokens:[c,u],flags:As.JsonEscape}).getStream(),m=new AbortController,h=setTimeout(()=>m.abort(),yf);try{let w=await fetch(`${this.#n}/engine?structure=base64-payload`,{method:"POST",headers:{"content-type":"application/json"},body:p,signal:m.signal});this.#r.debug&&ks.log.debug({message:"AkamaiApiSecurityPlugin: Dispatched entry",status:w.status,responseText:await w.text()})}catch(w){this.#r.debug&&ks.log.debug({message:`AkamaiApiSecurityPlugin: Error dispatching entry '${w.message}'`})}finally{clearTimeout(h)}},"#finalizeDispatch");#i=s(async(e,t,r,o,i,a)=>{let c=new URL(t.url),u=t.headers.get("true-client-ip")??"";return{ip:{v:vf(u),src:u,dst:"1.1.1.1"},tcp:{src:0,dst:Rf(c)},http:{v:i.incomingRequestProperties.httpProtocol?.replace("HTTP/","")||"1.1",request:{ts:a,method:t.method,url:c.pathname+c.search,headers:Object.fromEntries(t.headers.entries()),body:o.getSafeToken()},response:{ts:Date.now(),status:e.status,headers:Object.fromEntries(e.headers.entries()),body:r.getSafeToken()}},source:{type:_s.type,index:this.#r.index,version:_s.version,key:this.#r.key,resource:{type:"ZUPLO",properties:{account:Se.ZUPLO_ACCOUNT_NAME??"",project:Se.ZUPLO_PROJECT_NAME??"",environment:Se.ZUPLO_ENVIRONMENT_NAME??"",route:i.route.path}}}}},"#generateStreamTemplate")};function Rf(n){return n.port?parseInt(n.port):n.protocol==="https:"?443:80}s(Rf,"guessPort");function vf(n){return n.includes("::")||(n.match(/:/g)||[]).length>1?"6":"4"}s(vf,"detectIPVersion");function xf(n){let e=n.replace(/\/+$/,"");return e.startsWith("http://")||e.startsWith("https://")?e:`https://${e}`}s(xf,"normalizeHostname");var br=class{static{s(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new f("BackgroundDispatcher: options.msDelay is required");this.#e=new ie(t.name??"",t.msDelay,e)}enqueue=s(e=>{this.#e.enqueue(e),It().waitUntil(this.#e.waitUntilFlushed())},"enqueue")};var Ns,it=class{static{s(this,"RequestLoggerCore")}constructor(e,t){let o=(e.batchPeriodSeconds??.01)*1e3;this.#n=new br(this.#t,{msDelay:o}),this.#e=e,this.initialize(t)}initialize(e){e.addRequestHook((t,r)=>{Ns=r;let o=Date.now();return r.addResponseSendingFinalHook(async i=>{let a={deploymentName:y.instance.deploymentName??"",instanceId:y.instance.instanceId,systemUserAgent:y.instance.systemUserAgent,requestStartTime:new Date(o),durationMs:Date.now()-o},c=await this.#e.generateLogEntry(i,t,r,a);this.#n.enqueue(c)}),t})}#e;#t=s(async e=>{if(e.length!==0)try{await this.#e.dispatchFunction(e)}catch(t){Pf(t,this.#e.name)}},"#dispatch");#n};function Pf(n,e){if(!Ns){let r=It(),o=se({level:"error",messages:[`RequestLoggerCore '${e}': No context available to log user errors`]});r.waitUntil(o);return}let t;n instanceof Error?t={message:n.message,status:-1,details:n.stack??""}:t=n,Ns.log.error(`RequestLoggerCore '${e}': Error dispatching log entries.`,t)}s(Pf,"logError");var Fu="plugin.azure-blob-request-logger",If=s(()=>`${new Date().toISOString().replace(/[:-]/g,"-").replace("T","-").split(".")[0]}-${y.instance.instanceId}.csv`,"defaultGenerateBlobName"),ju,Ds=class extends Ee{static{s(this,"AzureBlobPlugin")}constructor(e){super(),this.#e=e,g(Fu)}async initialize(e){new it({name:Fu,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=s(async e=>{if(e.length===0)return;let t=Ef(e[0]),r=Sf(e,t),i=(this.#e.generateBlobName??If)(e);await Cf(r,this.#e,i)},"#dispatch")};function Ef(n){return Object.keys(n)}s(Ef,"getHeaders");function Tf(n){if(n==null)return"";let e=String(n);return(e.includes('"')||e.includes(",")||e.includes(`
|
|
77
77
|
`)||e.includes("\r"))&&(e=e.replace(/"/g,'""'),e=`"${e}"`),e}s(Tf,"escapeCsvValue");function Sf(n,e){let t=[];t.push(e.join(","));for(let r of n){let o=[];for(let i of e){let a=r[i];o.push(Tf(a))}t.push(o.join(","))}return t.join(`
|
|
78
78
|
`)}s(Sf,"generateCsvContent");async function Cf(n,e,t){let{sasUrl:r}=e,o=r.split("?"),i=`${o[0]}/${t}?${o[1]}`;try{let a=await j.fetch(i,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/csv"},body:n});a.ok||(Ms({message:a.statusText,status:a.status,details:await a.text()}),Ms({message:a.statusText,status:a.status,details:await a.text()}))}catch(a){Ms(a)}}s(Cf,"uploadToAzureBlobStorage");function Ms(n){if(!ju){let t=It(),r=se({level:"error",messages:["AzureBlobCsvPlugin: No context available to log user errors"]});t.waitUntil(r);return}let e;n instanceof Error?e={message:n.message,status:-1,details:n.stack??""}:e=n,ju.log.error("AzureBlobCsvPlugin: Error uploading to Azure Blob Storage",e)}s(Ms,"logError");var zu="plugin.azure-event-hubs-request-logger",Of=60*60,Af=5*60;function Bu(){return Math.floor(Date.now()/1e3)}s(Bu,"nowEpochSeconds");var Zs=class extends Ee{static{s(this,"AzureEventHubsRequestLoggerPlugin")}#e;#t;#n=null;constructor(e){super(),this.#e=e,this.#t=this.#r(e.connectionString),g(zu)}#r(e){let t=e.split(";"),r=new Map;for(let i of t){let[a,...c]=i.split("=");a&&c.length>0&&r.set(a,c.join("="))}return{endpoint:r.get("Endpoint")||"",sharedAccessKeyName:r.get("SharedAccessKeyName")||"",sharedAccessKey:r.get("SharedAccessKey")||"",entityPath:r.get("EntityPath")||""}}async#o(e,t,r){let o=new TextEncoder,i=e.replace(/^https?:\/\//,""),a=encodeURIComponent(i),u=Bu()+Of,l=`${a}
|
|
79
|
-
${u}`,d={name:"HMAC",hash:{name:"SHA-256"}},p=await crypto.subtle.importKey("raw",o.encode(r),d,!1,["sign"]),m=await crypto.subtle.sign("HMAC",p,o.encode(l)),h=new Uint8Array(m),
|
|
79
|
+
${u}`,d={name:"HMAC",hash:{name:"SHA-256"}},p=await crypto.subtle.importKey("raw",o.encode(r),d,!1,["sign"]),m=await crypto.subtle.sign("HMAC",p,o.encode(l)),h=new Uint8Array(m),w=btoa(String.fromCharCode(...h)),b=encodeURIComponent(w);return{token:`SharedAccessSignature sr=${a}&sig=${b}&se=${u}&skn=${t}`,expiryEpochSeconds:u}}async#i(){let e=Bu();if(this.#n&&e<this.#n.expiryEpochSeconds-Af)return this.#n.token;let t=this.#t.entityPath?this.#t.entityPath:(this.#e.eventHubName??"").trim();if(!t)throw new Error("No entity path - either set EntityPath in the connection string or supply eventHubName");let o=`${this.#t.endpoint.replace(/\/$/,"").toLowerCase()}/${t}`,i=await this.#o(o,this.#t.sharedAccessKeyName,this.#t.sharedAccessKey);return this.#n=i,i.token}async initialize(e){new it({name:zu,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#s},e)}#s=s(async e=>{if(e.length===0)return;let t=this.#t.entityPath?this.#t.entityPath:(this.#e.eventHubName??"").trim(),o=`https://${this.#t.endpoint.replace(/\/$/,"").replace(/^sb:\/\//,"")}/${t}/messages?timeout=60`,i=await this.#i(),a=await fetch(o,{method:"POST",headers:{Authorization:i,"Content-Type":"application/json"},body:JSON.stringify(e)});if(!a.ok)throw new Error(`AzureEventHubsRequestLoggerPlugin: Failed to send logs to ${o}
|
|
80
80
|
Status: ${a.status} - ${a.statusText}
|
|
81
81
|
Body: ${await a.text()}`)},"#dispatch")};var _f=s(async(n,e,t,r)=>({deploymentName:r.deploymentName,timestamp:r.requestStartTime.toISOString(),requestId:t.requestId,routePath:t.route.path,url:e.url,colo:t.incomingRequestProperties.colo,city:t.incomingRequestProperties.city,country:t.incomingRequestProperties.country,continent:t.incomingRequestProperties.continent,latitude:t.incomingRequestProperties.latitude,longitude:t.incomingRequestProperties.longitude,postalCode:t.incomingRequestProperties.postalCode,metroCode:t.incomingRequestProperties.metroCode,region:t.incomingRequestProperties.region,regionCode:t.incomingRequestProperties.regionCode,timezone:t.incomingRequestProperties.timezone,asn:t.incomingRequestProperties.asn?.toString(),asOrganization:t.incomingRequestProperties.asOrganization,statusCode:n.status,durationMs:r.durationMs,method:e.method,userSub:e.user?.sub,instanceId:r.instanceId,clientIP:e.headers.get("true-client-ip")??void 0,zuploUserAgent:r.systemUserAgent}),"defaultGenerateHydrolixEntry"),Gu="plugin.hydrolix-request-logger",qs=class extends Ee{static{s(this,"HydrolixRequestLoggerPlugin")}constructor(e){super(),e.batchPeriodSeconds||(e.batchPeriodSeconds=1),this.#e=e,g(Gu)}async initialize(e){new it({name:Gu,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=s(async e=>{if(e.length===0)return;let t={"x-hdx-table":this.#e.table,"x-hdx-transform":this.#e.transform,"content-type":"application/json"};this.#e.token&&(t["x-hdx-token"]=this.#e.token,t.authorization=`Basic ${btoa(`${this.#e.username}:${this.#e.password}`)}`),await j.fetch(`https://${this.#e.hostname}/ingest/event`,{method:"POST",headers:t,body:JSON.stringify(e)})},"#dispatch")};var kf="plugin.request-logger",$s=class extends Ee{static{s(this,"RequestLoggerPlugin")}constructor(e){super(),this.#e=e,g(kf)}async initialize(e){new it(this.#e,e)}#e};var Us=class extends Error{static{s(this,"StripeError")}message;type;raw;rawType;headers;requestId;code;doc_url;param;detail;statusCode;charge;decline_code;payment_method_type;payment_intent;payment_method;setup_intent;source;constructor(e={}){super(e.message),this.type=this.constructor.name,this.raw=e,this.rawType=e.type,this.code=e.code,this.doc_url=e.doc_url,this.param=e.param,this.detail=e.detail,this.headers=e.headers,this.requestId=e.requestId,this.statusCode=e.statusCode,this.message=e.message,this.charge=e.charge,this.decline_code=e.decline_code,this.payment_intent=e.payment_intent,this.payment_method=e.payment_method,this.payment_method_type=e.payment_method_type,this.setup_intent=e.setup_intent,this.source=e.source}},st=class extends Us{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var Lf="v1",Nf=300;async function Vu(n,e,t,r=Nf,o){return await Df(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}s(Vu,"constructEventAsync");function Mf(n,e){return`${e.timestamp}.${n}`}s(Mf,"makeHMACContent");async function Df(n,e,t,r,o){let{decodedHeader:i,decodedPayload:a,details:c,suspectPayloadType:u}=Zf(n,e,Lf),l=/\s/.test(t),d=await Hf(Mf(a,c),t);return qf(a,i,c,d,r,u,l,o)}s(Df,"verifyHeaderAsync");function Zf(n,e,t){if(!n)throw new st(e,n,{message:"No webhook payload was provided."});let r=typeof n!="string"&&!(n instanceof Uint8Array),o=new TextDecoder("utf8"),i=n instanceof Uint8Array?o.decode(n):n;if(Array.isArray(e))throw new Error("Unexpected: An array was passed as a header, which should not be possible for the stripe-signature header.");if(e==null||e=="")throw new st(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,c=$f(a,t);if(!c||c.timestamp===-1)throw new st(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!c.signatures.length)throw new st(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:c,suspectPayloadType:r}}s(Zf,"parseEventDetails");function qf(n,e,t,r,o,i,a,c){let u=!!t.signatures.filter(m=>Uf(m,r)).length,l=`
|
|
82
82
|
Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
|
|
@@ -87,11 +87,11 @@ Signature verification is impossible without access to the original signed mater
|
|
|
87
87
|
`+d}):new st(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
|
|
88
88
|
If a webhook request is being forwarded by a third-party tool, ensure that the exact request body, including JSON formatting and new line style, is preserved.
|
|
89
89
|
`+l+`
|
|
90
|
-
`+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new st(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(qf,"validateComputedSignature");function $f(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}s($f,"parseHeader");function Uf(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}s(Uf,"secureCompare");async function Hf(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),i=new Uint8Array(o),a=new Array(i.length);for(let c=0;c<i.length;c++)a[c]=Hs[i[c]];return a.join("")}s(Hf,"computeHMACSignatureAsync");var Hs=new Array(256);for(let n=0;n<Hs.length;n++)Hs[n]=n.toString(16).padStart(2,"0");function te(n,e,t="policy",r){let o=`${t} '${e}'`;if(!Zt(n))throw new f(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let i=s((u,l,d)=>{let p=n[u],m=r?`${r}.${String(u)}`:String(u);if(!(d&&p===void 0)){if(p===void 0)throw new f(`Value of '${m}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new f(`Value of '${m}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new f(`Value of '${m}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new f(`Value of '${m}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new f(`Value of '${m}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=s((u,l)=>(i(u,l,!0),{optional:a,required:c}),"optional"),c=s((u,l)=>(i(u,l,!1),{optional:a,required:c}),"required");return{optional:a,required:c}}s(te,"optionValidator");var wr=class extends ye{static{s(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){te(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await Vu(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,u=/Note:(.*)/g.exec(a);i=u?u[1].trim():a,i.startsWith("No signatures found matching the expected signature for payload")&&(i="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",i),T.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function Wu(n){return n!==null&&typeof n=="object"&&"id"in n&&qe(n.id)&&"type"in n&&qe(n.type)}s(Wu,"isStripeWebhookEvent");var Ff={getSubscription:s(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await j.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw t.error(i,o),new k(i)}return o},"getSubscription"),getCustomer:s(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await j.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw t.error(i,o),new k(i)}return o},"getCustomer"),getUpcomingInvoice:s(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await j.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(i,o),new k(i)}return o},"getUpcomingInvoice")},ho=Ff;var Fs="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ju="My API Key";async function Ku({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:c}=y.instance,u=new URL(`/v1/buckets/${n}/consumers`,Fs);u.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ju,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(a)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,m),new k(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}s(Ku,"createConsumer");async function Qu({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=y.instance,c=new URL(`/v1/buckets/${n}/consumers`,Fs);c.searchParams.set("with-api-key","true");let u=crypto.randomUUID(),l={name:u,description:Ju,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(i)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw i.log.error(m,p),new k(m)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:u,stripeSubscriptionId:e,stripeProductId:t}),u}s(Qu,"createConsumerInvite");async function Yu({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=y.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,Fs);o.searchParams.set("with-api-key","true");let i=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),c="Error invalidating API Key Consumer";throw t.log.error(c,a),new k(c)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(Yu,"deleteConsumer");async function Xu({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:c,metadata:u,trial:l}){let d={status:c,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:u,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:m}=y.instance;if(!un(p))throw new ae("No Zuplo JWT token set.");let h=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(n)},`${m}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!h.ok){let x=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,b,P="";try{b=await h.json(),P=b.detail??b.title}catch{b={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:h.status,detail:h.statusText}}throw n.log.error(x,b),new k(`${x} ${P}`)}n.log.info("Successfully created monetization subscription.",d)}s(Xu,"createSubscription");async function Tn({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!un(o))throw new ae("No Zuplo JWT token set.");let a=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(n)},`${i}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let c=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,u,l="";try{u=await a.json(),l=u.detail??u.title}catch{u={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,u),new k(`${c} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}s(Tn,"updateSubscription");async function Sn({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!un(o))throw new ae("No Zuplo JWT token set.");let a=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let u=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,l),new k(`${u} ${d}`)}let c=await a.json();if(c.data.length===0){let u=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(u),new k(u)}if(c.data[0].customerExternalId!==t){let u=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(u),new k(u)}return c.data[0]}s(Sn,"getSubscription");var be="Skipping since we're unable to process the webhook event.",kt="Successfully processed the webhook event",Ze="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function yo(n){return n.replaceAll("_","-")}s(yo,"stripeStatusToMeteringStatus");function tn(n){return new Date(n*1e3).toISOString()}s(tn,"unixTimestampToISOString");async function js(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),T.ok(n,e,{title:be,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:be,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ze});let c=i.product,u,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,u=await Ku({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await ho.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.ok(n,e,{title:be,detail:"Invalid Stripe API result. Expected customer to contain email address."});u=await Qu({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),T.ok(n,e,{title:be,detail:p.message})}if(!u)return T.ok(n,e,{title:be,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=yo(t.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}});let h;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(h={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:tn(t.data.object.trial_end),trialStartDate:tn(t.data.object.trial_start)}),await Xu({context:e,stripeProductId:c,stripeSubscriptionId:o,customerKey:u,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m,trial:h})}catch(p){return await Yu({apiKeyBucketName:r.apiKeyBucketName,consumerId:u,context:e}),T.ok(n,e,{title:be,detail:p.message})}return T.ok(n,e,{title:kt})}s(js,"onCustomerSubscriptionCreated");async function zs(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:be,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ze});try{let a=await Sn({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await Tn({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.ok(n,e,{title:be,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ze})}return T.ok(n,e,{title:kt})}s(zs,"onCustomerSubscriptionDeleted");async function Bs(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:be,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ze});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let c=await Sn({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),u=yo(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=tn(t.data.object.trial_end)),await Tn({context:e,meteringSubscriptionId:c.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u,planExternalIds:c.planExternalIds,trialEndDate:l}})}catch(c){return T.ok(n,e,{title:be,detail:`The event 'customer.subscription.updated' could not be processed. ${c.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ze})}return T.ok(n,e,{title:kt})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let c=await Sn({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),u=t.data.object.plan.product,d=(await ho.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===u),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Tn({context:e,meteringSubscriptionId:c.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c.status,planExternalIds:[u],prorate:p}})}catch(c){return T.ok(n,e,{title:be,detail:`The event 'customer.subscription.updated' could not be processed. ${c.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ze})}return T.ok(n,e,{title:kt})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let c=await Sn({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),u={cancellation:{cancel_at:t.data.object.cancel_at?tn(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?tn(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;c.metadata?l={...c.metadata,...u}:l=u,await Tn({context:e,meteringSubscriptionId:c.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c.status,planExternalIds:c.planExternalIds,metadata:l}})}catch(c){return T.ok(n,e,{title:be,detail:`The event 'customer.subscription.updated' could not be processed. ${c.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ze})}return T.ok(n,e,{title:kt})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),T.ok(n,e,{title:be,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ze})}s(Bs,"onCustomerSubscriptionUpdated");var el=class extends Nr{constructor(t){super();this.options=t;g("monetization.stripe")}static{s(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=s(async(u,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Se.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new f("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new ae("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!jf(m))throw new f(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let h=await u.json();if(!Wu(h))return T.ok(u,l,{title:be,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ze});switch(l.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await js(u,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Bs(u,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await zs(u,l,h,{meteringBucketId:d});default:return T.ok(u,l,{title:be,detail:`Event '${h.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ze})}},"stripeWebhookHandler"),i=_c({inboundPolicies:[new wr({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});te(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new Te({processors:[ke,i],handler:o,gateway:r}),c=new xe({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(c,a.execute)}};function jf(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(jf,"isMetricsRegion");var nl=new WeakMap,tl={},Gs=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){nl.set(e,t)}};async function zf(n,e,t,r){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new f(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=vt(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=nl.get(e),c=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new k(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);c=ct(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},m=tl[t.apiKey];if(!m){let h=t.apiKey,x=n.headers.get("zm-test-id")??"";m=new ie("amberflo-ingest-meter",10,async b=>{try{let P=t.url??"https://app.amberflo.io/ingest",N=await j.fetch(P,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":x}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${N.status}: ${await N.text()}`)}catch(P){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${P.message}`),P}}),tl[h]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),n}s(zf,"AmberfloMeteringInboundPolicy");async function nn(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(nn,"sha256");var rl=new Map;async function ge(n,e,t){let r,o=`${n}-${e}`,i=rl.get(o);return i!==void 0?r=i:(r=`zuplo-policy-${await nn(JSON.stringify({policyName:n,options:t}))}`,rl.set(n,r)),r}s(ge,"getPolicyCacheName");var ol="key-metadata-cache-type";function Bf(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(Bf,"getKeyValue");async function Vs(n,e,t,r){if(g("policy.inbound.api-key"),!t.bucketName)if(Se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(N=>o.allowUnauthenticatedRequests?n:T.unauthorized(n,e,{detail:N}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let c=Bf(a,o);if(!c||c==="")return i("No key present");let u=await Gf(c),l=await ge(r,void 0,o),d=new me(l,e),p=await d.get(u);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==ol&&ne.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let m={key:c},h=new Headers({"content-type":"application/json"});Xe(h,e.requestId);let x=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:h,body:JSON.stringify(m)});if(x.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(x.status!==200){try{let N=await x.text(),A=JSON.parse(N);e.log.error("Unexpected response from key service",A)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${x.status}`)}let b=await x.json(),P={isValid:!0,typeId:ol,user:{apiKeyId:b.id,sub:b.name,data:b.metadata}};return n.user=P.user,d.put(u,P,o.cacheTtlSeconds),n}s(Vs,"ApiKeyInboundPolicy");async function Gf(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Gf,"hashValue");var Vf=Vs;var il=Symbol("aserto-authz-resource-context"),Ws=class extends ye{static{s(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){fe.set(e,il,t)}constructor(e,t){if(super(e,t),te(e,t).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new f(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,t){if(!this.cache){let u=await ge(this.policyName,void 0,this.options);this.cache=new me(u,t)}let r=s(u=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:u}),"forbiddenResponse");if(!e.user)return t.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),T.unauthorized(e,t);let o=fe.get(t,il),i;o?.policyInstance?i=o.policyInstance:this.options.policyName?i={name:this.options.policyName}:i={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?ct(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,c={identityContext:o?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:o?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:o?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:i};try{t.log.debug("Aserto Request",c);let u=await j.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(c)});if(u.status!==200){let d=`Error calling Aserto service. Status: ${u.status}`;try{d=(await u.json()).message}catch{}return t.log.error(`${this.policyType} '${this.policyName}' - ${d}`),u.status>=400&&u.status<500?r(d):T.internalServerError(e,t)}let l=await u.json();return t.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),r("The request was not authorized."))}catch(u){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,u),T.internalServerError(e,t)}}};import{createRemoteJWKSet as Jf,jwtVerify as al}from"jose";import{createLocalJWKSet as Wf}from"jose";var Js=class{constructor(e,t,r){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{s(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof Ks&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",y.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Wf(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let i,a,c=!1;typeof AbortController=="function"&&(i=new AbortController,a=setTimeout(()=>{c=!0,i.abort()},t));let u=await j.fetch(e.href,{signal:i?i.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw c?new Qs("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),u.status!==200)throw new Cn("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await u.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new Cn("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function sl(n,e,t){let r=new Js(n,e,t);return async(o,i)=>r.getKey(o,i)}s(sl,"createRemoteJWKSet");var Cn=class extends k{static{s(this,"JWKSError")}},Ks=class extends Cn{static{s(this,"JWKSNoMatchingKey")}},Qs=class extends Cn{static{s(this,"JWKSTimeout")}};var bo={},Kf=s((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");if(!bo[r.jwkUrl]){let i=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(i=r.useExperimentalInMemoryCache),i){let a=await ge(n,void 0,r),c=new me(a,e);bo[r.jwkUrl]=sl(new URL(r.jwkUrl),c,r.headers?{headers:r.headers}:void 0)}else bo[r.jwkUrl]=Jf(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await al(t,bo[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Qf=s(async(n,e)=>{let t;if(e.secret===void 0)throw new f("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);t=new Uint8Array(i)}else t=e.secret;let{payload:r}=await al(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),Me=s(async(n,e,t,r)=>{g("policy.inbound.open-id-jwt-auth");let o=t.authHeader??"Authorization",i=n.headers.get(o),a="bearer ",c=s(h=>T.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?Kf(r,e):Qf,d=await s(async()=>{if(!i)return c("No authorization header");if(i.toLowerCase().indexOf(a)!==0)return c("Invalid bearer token format for authorization header");let h=i.substring(a.length);if(!h||h.length===0)return c("No bearer token on authorization header");try{return await u(h,t)}catch(x){let b=new URL(n.url);return"code"in x&&x.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${b.pathname} `,x):e.log.warn(`Invalid token on: ${n.method} ${b.pathname}`,x),c("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",m=d[p];return m?(n.user={sub:m,data:d},n):c(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var Yf=s(async(n,e,t,r)=>(g("policy.inbound.auth0-jwt-auth"),Me(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var cl=new Map;function Xf(n){let e=[],t=0;for(;t<n.length;){if(n[t]==="."){t++;continue}if(n[t]==="["){for(t++;t<n.length&&/\s/.test(n[t]);)t++;let r=n[t];if(r!=='"'&&r!=="'"){for(;t<n.length&&n[t]!=="]";)t++;t++;continue}t++;let o=t;for(;t<n.length&&n[t]!==r;)t++;let i=n.substring(o,t);for(e.push(i),t++;t<n.length&&/\s/.test(n[t]);)t++;n[t]==="]"&&t++}else{let r=t;for(;t<n.length&&n[t]!=="."&&n[t]!=="[";)t++;let o=n.substring(r,t).trim();o.length>0&&e.push(o)}}return e}s(Xf,"parsePropertyPath");function wo(n,e){let t="$authzen-prop(";if(!n.startsWith(t)||!n.endsWith(")"))return n;let r=n.slice(t.length,-1),o=cl.get(r);o||(o=Xf(r),cl.set(r,o));let i=e;for(let a of o){if(i==null)return;typeof i.get=="function"?i=i.get(a):i=i[a]}return i}s(wo,"evaluateAuthzenProp");var ul=Symbol("AUTHZEN_CONTEXT_DATA_52a5cf22-d922-4673-9815-6dc3d49071d9"),Ys=class n extends ye{static{s(this,"AuthZenInboundPolicy")}#e;#t;constructor(e,t){if(super(e,t),te(e,t).required("authorizerHostname","string").optional("authorizerAuthorizationHeader","string").optional("subject","object").optional("resource","object").optional("action","object").optional("throwOnError","boolean"),e.subject&&!e.subject.type)throw new f(`${this.policyType} '${this.policyName}' - subject.type is required.`);if(e.subject&&!e.subject.id)throw new f(`${this.policyType} '${this.policyName}' - subject.id is required.`);if(e.resource&&!e.resource.type)throw new f(`${this.policyType} '${this.policyName}' - resource.type is required.`);if(e.resource&&!e.resource.id)throw new f(`${this.policyType} '${this.policyName}' - resource.id is required.`);if(e.action&&!e.action.name)throw new f(`${this.policyType} '${this.policyName}' - action.name is required.`);this.#e=(e.authorizerHostname.startsWith("https://")?e.authorizerHostname:`https://${e.authorizerHostname}`)+"/access/v1/evaluation";try{new URL(this.#e)}catch(r){throw new f(`${this.policyType} '${this.policyName}' - authorizerUrl '${this.#e}' is not valid
|
|
90
|
+
`+d});let p=Math.floor((typeof c=="number"?c:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new st(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(qf,"validateComputedSignature");function $f(n,e){return typeof n!="string"?null:n.split(",").reduce((t,r)=>{let o=r.split("=");return o[0]==="t"&&(t.timestamp=parseInt(o[1],10)),o[0]===e&&t.signatures.push(o[1]),t},{timestamp:-1,signatures:[]})}s($f,"parseHeader");function Uf(n,e){if(n.length!==e.length)return!1;let t=n.length,r=0;for(let o=0;o<t;++o)r|=n.charCodeAt(o)^e.charCodeAt(o);return r===0}s(Uf,"secureCompare");async function Hf(n,e){let t=new TextEncoder,r=await crypto.subtle.importKey("raw",t.encode(e),{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]),o=await crypto.subtle.sign("hmac",r,t.encode(n)),i=new Uint8Array(o),a=new Array(i.length);for(let c=0;c<i.length;c++)a[c]=Hs[i[c]];return a.join("")}s(Hf,"computeHMACSignatureAsync");var Hs=new Array(256);for(let n=0;n<Hs.length;n++)Hs[n]=n.toString(16).padStart(2,"0");function te(n,e,t="policy",r){let o=`${t} '${e}'`;if(!Zt(n))throw new f(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let i=s((u,l,d)=>{let p=n[u],m=r?`${r}.${String(u)}`:String(u);if(!(d&&p===void 0)){if(p===void 0)throw new f(`Value of '${m}' on ${o} is required, but no value was set. If using an environment variable, check that it is set correctly.`);if(l==="array"&&Array.isArray(p))throw new f(`Value of '${m}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new f(`Value of '${m}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new f(`Value of '${m}' on ${o} must be a non-empty string. The value received is empty. If using an environment variable, check that it is set correctly.`);if(typeof p=="number"&&isNaN(p))throw new f(`Value of '${m}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=s((u,l)=>(i(u,l,!0),{optional:a,required:c}),"optional"),c=s((u,l)=>(i(u,l,!1),{optional:a,required:c}),"required");return{optional:a,required:c}}s(te,"optionValidator");var wr=class extends ye{static{s(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){te(this.options,this.policyName).required("signingSecret","string").optional("tolerance","number");let r=e.headers.get("stripe-signature");try{let o=await e.clone().text();await Vu(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,u=/Note:(.*)/g.exec(a);i=u?u[1].trim():a,i.startsWith("No signatures found matching the expected signature for payload")&&(i="The Stripe Webhook Signature Secret provided is incorrect and does not match to the signature on the event received. Make sure your Zuplo configuration is correct.")}return t.log.error("Error validating stripe webhook",i),T.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function Wu(n){return n!==null&&typeof n=="object"&&"id"in n&&qe(n.id)&&"type"in n&&qe(n.type)}s(Wu,"isStripeWebhookEvent");var Ff={getSubscription:s(async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await j.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw t.error(i,o),new k(i)}return o},"getSubscription"),getCustomer:s(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await j.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw t.error(i,o),new k(i)}return o},"getCustomer"),getUpcomingInvoice:s(async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await j.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(i,o),new k(i)}return o},"getUpcomingInvoice")},ho=Ff;var Fs="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Ju="My API Key";async function Ku({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:c}=y.instance,u=new URL(`/v1/buckets/${n}/consumers`,Fs);u.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Ju,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(a)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${c}`,"content-type":"application/json"},body:JSON.stringify(d)}),m=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,m),new k(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}s(Ku,"createConsumer");async function Qu({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=y.instance,c=new URL(`/v1/buckets/${n}/consumers`,Fs);c.searchParams.set("with-api-key","true");let u=crypto.randomUUID(),l={name:u,description:Ju,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(i)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let m="Error creating API Key Consumer";throw i.log.error(m,p),new k(m)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:u,stripeSubscriptionId:e,stripeProductId:t}),u}s(Qu,"createConsumerInvite");async function Yu({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=y.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,Fs);o.searchParams.set("with-api-key","true");let i=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(t)},o.toString(),{method:"DELETE",headers:{Authorization:`Bearer ${r}`,"content-type":"application/json"},body:JSON.stringify({})});if(i.status!==204){let a=await i.json(),c="Error invalidating API Key Consumer";throw t.log.error(c,a),new k(c)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(Yu,"deleteConsumer");async function Xu({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:c,metadata:u,trial:l}){let d={status:c,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:u,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:m}=y.instance;if(!un(p))throw new ae("No Zuplo JWT token set.");let h=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(n)},`${m}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!h.ok){let w=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,b,P="";try{b=await h.json(),P=b.detail??b.title}catch{b={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:h.status,detail:h.statusText}}throw n.log.error(w,b),new k(`${w} ${P}`)}n.log.info("Successfully created monetization subscription.",d)}s(Xu,"createSubscription");async function Tn({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!un(o))throw new ae("No Zuplo JWT token set.");let a=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(n)},`${i}/internal/v1/metering/${t}/subscriptions/${e}`,{headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"PATCH",body:JSON.stringify(r)});if(!a.ok){let c=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,u,l="";try{u=await a.json(),l=u.detail??u.title}catch{u={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(c,u),new k(`${c} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}s(Tn,"updateSubscription");async function Sn({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!un(o))throw new ae("No Zuplo JWT token set.");let a=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let u=`Unable to retrieve the monetization subscription for Stripe subscription '${e}'.`,l,d="";try{l=await a.json(),d=l.detail??l.title}catch{l={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,l),new k(`${u} ${d}`)}let c=await a.json();if(c.data.length===0){let u=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(u),new k(u)}if(c.data[0].customerExternalId!==t){let u=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(u),new k(u)}return c.data[0]}s(Sn,"getSubscription");var be="Skipping since we're unable to process the webhook event.",kt="Successfully processed the webhook event",Ze="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function yo(n){return n.replaceAll("_","-")}s(yo,"stripeStatusToMeteringStatus");function tn(n){return new Date(n*1e3).toISOString()}s(tn,"unixTimestampToISOString");async function js(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.plan;if(!i||!i.product)return e.log.warn(`Invalid Stripe API result. Expected event '${t.id}' to have a plan data.`),T.ok(n,e,{title:be,detail:"Invalid Stripe API result. Expected event to have a plan data."});let a=t.data.object.customer;if(!a)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:be,detail:`This subscription event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ze});let c=i.product,u,l,d;try{if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_email&&t.data.object.metadata.zuplo_created_by_sub)l=t.data.object.metadata.zuplo_created_by_email,d=t.data.object.metadata.zuplo_created_by_sub,u=await Ku({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await ho.getCustomer({logger:e.log,stripeSecretKey:r.stripeSecretKey,customerId:a});if(!p.email)return e.log.warn(`Invalid Stripe API result. Expected customer '${a}' to contain email address.`),T.ok(n,e,{title:be,detail:"Invalid Stripe API result. Expected customer to contain email address."});u=await Qu({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:c,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),T.ok(n,e,{title:be,detail:p.message})}if(!u)return T.ok(n,e,{title:be,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=yo(t.data.object.status),m;l&&d&&(m={subscriber:{sub:d,email:l}});let h;t.data.object.trial_end!==null&&t.data.object.trial_start!==null&&t.data.object.trial_settings&&t.data.object.trial_settings.end_behavior&&(t.data.object.trial_settings.end_behavior.missing_payment_method==="cancel"||t.data.object.trial_settings.end_behavior.missing_payment_method==="pause")&&(h={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:tn(t.data.object.trial_end),trialStartDate:tn(t.data.object.trial_start)}),await Xu({context:e,stripeProductId:c,stripeSubscriptionId:o,customerKey:u,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:m,trial:h})}catch(p){return await Yu({apiKeyBucketName:r.apiKeyBucketName,consumerId:u,context:e}),T.ok(n,e,{title:be,detail:p.message})}return T.ok(n,e,{title:kt})}s(js,"onCustomerSubscriptionCreated");async function zs(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to have '.data.object.id' be the subscription ID.`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:be,detail:`This 'customer.subscription.deleted' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ze});try{let a=await Sn({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await Tn({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.ok(n,e,{title:be,detail:`The event 'customer.subscription.deleted' could not be processed. ${a.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. `+Ze})}return T.ok(n,e,{title:kt})}s(zs,"onCustomerSubscriptionDeleted");async function Bs(n,e,t,r){let o=t.data.object.id;if(!o)return e.log.warn(`Invalid Stripe webhook event. Expected event '${t.id}' to include '.data.object.id' as the subscription ID.`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.id' to be the subscription ID."});let i=t.data.object.customer;if(!i)return e.log.warn(`Invalid Stripe webhook event. Expected '.data.object.customer' to be provided by event '${t.id}'`),T.ok(n,e,{title:be,detail:"Invalid Stripe webhook event. Expected '.data.object.customer' to be provided"});if(t.data.object.metadata&&t.data.object.metadata.zuplo_created_by_deploymentName&&t.data.object.metadata.zuplo_created_by_deploymentName!==y.instance.deploymentName)return e.log.warn(`Subscription event '${t.id}' will not be handled since it was not issued for this Zuplo environment. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.`),T.ok(n,e,{title:be,detail:`This 'customer.subscription.updated' event is not meant to be handled by this environment's Stripe monetization plugin. It was intended for '${t.data.object.metadata.zuplo_created_by_deploymentName}'.This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ze});if(t.data.previous_attributes){let a=t.data.previous_attributes;if(a.status&&a.status!==t.data.object.status){try{e.log.debug(`Processing subscription status change from Stripe event '${t.id}'.`);let c=await Sn({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),u=yo(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=tn(t.data.object.trial_end)),await Tn({context:e,meteringSubscriptionId:c.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u,planExternalIds:c.planExternalIds,trialEndDate:l}})}catch(c){return T.ok(n,e,{title:be,detail:`The event 'customer.subscription.updated' could not be processed. ${c.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ze})}return T.ok(n,e,{title:kt})}if(a.plan&&a.plan.product!==t.data.object.plan.product){try{e.log.debug(`Processing subscription plan change from Stripe event '${t.id}'.`);let c=await Sn({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),u=t.data.object.plan.product,d=(await ho.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(m=>m.proration&&m.price.product===u),p=0;d.length===0?e.log.warn(`The plan change does not include proration details. Subscription event '${t.id}'`):p=parseFloat(d[0].unit_amount_excluding_tax)/d[0].price.unit_amount,await Tn({context:e,meteringSubscriptionId:c.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c.status,planExternalIds:[u],prorate:p}})}catch(c){return T.ok(n,e,{title:be,detail:`The event 'customer.subscription.updated' could not be processed. ${c.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ze})}return T.ok(n,e,{title:kt})}if((a.cancel_at||a.cancel_at===null)&&a.cancel_at!==t.data.object.cancel_at&&a.cancel_at_period_end&&a.cancel_at_period_end!==t.data.object.cancel_at_period_end&&(a.canceled_at||a.canceled_at===null)&&a.canceled_at!==t.data.object.canceled_at||a.cancellation_details&&(a.cancellation_details.comment||a.cancellation_details.comment===null||a.cancellation_details.feedback||a.cancellation_details.feedback===null||a.cancellation_details.reason||a.cancellation_details.reason===null)){try{e.log.debug(`Processing subscription cancellation details from Stripe event '${t.id}'.`);let c=await Sn({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),u={cancellation:{cancel_at:t.data.object.cancel_at?tn(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?tn(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;c.metadata?l={...c.metadata,...u}:l=u,await Tn({context:e,meteringSubscriptionId:c.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c.status,planExternalIds:c.planExternalIds,metadata:l}})}catch(c){return T.ok(n,e,{title:be,detail:`The event 'customer.subscription.updated' could not be processed. ${c.message} This can happen because of a misconfiguration of Stripe or your Zuplo API. However, it also could be a temporary condition that happens when a subscription is created due to events being sent out of order. `+Ze})}return T.ok(n,e,{title:kt})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),T.ok(n,e,{title:be,detail:"This 'customer.subscription.updated' event could not be processed. The Stripe monetization plugin only supports update events for subscription plan changes or subscription status changes."+Ze})}s(Bs,"onCustomerSubscriptionUpdated");var el=class extends Nr{constructor(t){super();this.options=t;g("monetization.stripe")}static{s(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=s(async(u,l)=>{if(this.options.__testMode===!0)return l.log.warn("Received Stripe webhook event of in test mode."),"success";let{meteringBucketId:d,apiKeyBucketName:p}=this.options;if(!d)if(Se.ZUPLO_METERING_SERVICE_BUCKET_ID)d=Se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new f("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(Se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=Se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new ae("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let m=this.options.primaryDataRegion??"us-central1";if(!jf(m))throw new f(`StripeMonetizationPlugin - The value '${m}' on the property 'primaryDataRegion' is invalid.`);let h=await u.json();if(!Wu(h))return T.ok(u,l,{title:be,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Ze});switch(l.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await js(u,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await Bs(u,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:m,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await zs(u,l,h,{meteringBucketId:d});default:return T.ok(u,l,{title:be,detail:`Event '${h.type}' could not be processed because it is not supported by Stripe monetization plugin webhook. This can happen because of a misconfiguration of Stripe or your Zuplo API.`+Ze})}},"stripeWebhookHandler"),i=_c({inboundPolicies:[new wr({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});te(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new Te({processors:[ke,i],handler:o,gateway:r}),c=new xe({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(c,a.execute)}};function jf(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(jf,"isMetricsRegion");var nl=new WeakMap,tl={},Gs=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){nl.set(e,t)}};async function zf(n,e,t,r){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new f(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=vt(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=nl.get(e),c=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new k(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);c=ct(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let u=a?.customerId??c;if(!u){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': customerId cannot be undefined`);return}let l=a?.meterApiName??t.meterApiName;if(!l){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterApiName cannot be undefined`);return}let d=a?.meterValue??t.meterValue;if(!d){e.log.error(`Error in AmberfloMeterInboundPolicy '${r}': meterValue cannot be undefined`);return}let p={customerId:u,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},m=tl[t.apiKey];if(!m){let h=t.apiKey,w=n.headers.get("zm-test-id")??"";m=new ie("amberflo-ingest-meter",10,async b=>{try{let P=t.url??"https://app.amberflo.io/ingest",N=await j.fetch(P,{method:"POST",body:JSON.stringify(b),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":w}});N.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${N.status}: ${await N.text()}`)}catch(P){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${P.message}`),P}}),tl[h]=m}m.enqueue(p),e.waitUntil(m.waitUntilFlushed())}}),n}s(zf,"AmberfloMeteringInboundPolicy");async function nn(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest({name:"SHA-256"},e);return[...new Uint8Array(t)].map(o=>o.toString(16).padStart(2,"0")).join("")}s(nn,"sha256");var rl=new Map;async function ge(n,e,t){let r,o=`${n}-${e}`,i=rl.get(o);return i!==void 0?r=i:(r=`zuplo-policy-${await nn(JSON.stringify({policyName:n,options:t}))}`,rl.set(n,r)),r}s(ge,"getPolicyCacheName");var ol="key-metadata-cache-type";function Bf(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(Bf,"getKeyValue");async function Vs(n,e,t,r){if(g("policy.inbound.api-key"),!t.bucketName)if(Se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=Se.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new f(`ApiKeyInboundPolicy '${r}' - no bucketName property provided`);let o={authHeader:t.authHeader??"authorization",authScheme:t.authScheme??"Bearer",bucketName:t.bucketName,cacheTtlSeconds:t.cacheTtlSeconds??60,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1,disableAutomaticallyAddingKeyHeaderToOpenApi:t.disableAutomaticallyAddingKeyHeaderToOpenApi??!1};if(o.cacheTtlSeconds<60)throw new f(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(N=>o.allowUnauthenticatedRequests?n:T.unauthorized(n,e,{detail:N}),"unauthorizedResponse"),a=n.headers.get(o.authHeader);if(!a)return i("No Authorization Header");if(!a.toLowerCase().startsWith(o.authScheme.toLowerCase()))return i("Invalid Authorization Scheme");let c=Bf(a,o);if(!c||c==="")return i("No key present");let u=await Gf(c),l=await ge(r,void 0,o),d=new me(l,e),p=await d.get(u);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==ol&&ne.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let m={key:c},h=new Headers({"content-type":"application/json"});Xe(h,e.requestId);let w=await Oe({retryDelayMs:5,retries:2,logger:ne.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:h,body:JSON.stringify(m)});if(w.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(w.status!==200){try{let N=await w.text(),A=JSON.parse(N);e.log.error("Unexpected response from key service",A)}catch{e.log.error("Invalid response from key service")}throw new k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${w.status}`)}let b=await w.json(),P={isValid:!0,typeId:ol,user:{apiKeyId:b.id,sub:b.name,data:b.metadata}};return n.user=P.user,d.put(u,P,o.cacheTtlSeconds),n}s(Vs,"ApiKeyInboundPolicy");async function Gf(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(Gf,"hashValue");var Vf=Vs;var il=Symbol("aserto-authz-resource-context"),Ws=class extends ye{static{s(this,"AsertoAuthZInboundPolicy")}cache;authorizationUrl;static setAuthorizationContext(e,t){fe.set(e,il,t)}constructor(e,t){if(super(e,t),te(e,t).required("tenantId","string").required("authorizerApiKey","string").required("serviceName","string").optional("policyName","string").optional("authorizerApiUrl","string").optional("allowUnauthorizedRequests","boolean").optional("userSubPropertyPath","string"),this.options.authorizerApiUrl)try{new URL(this.options.authorizerApiUrl)}catch{throw new f(`${this.policyType} '${this.policyName}' - Value of 'authorizerApiUrl' is not a valid URL. If using an environment variable, check that it is set correctly.`)}this.authorizationUrl=new URL("/api/v2/authz/is",this.options.authorizerApiUrl??"https://authorizer.prod.aserto.com")}async handler(e,t){if(!this.cache){let u=await ge(this.policyName,void 0,this.options);this.cache=new me(u,t)}let r=s(u=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:u}),"forbiddenResponse");if(!e.user)return t.log.error(`${this.policyType} '${this.policyName}' - User is not authenticated. An authentication policy must come before the authorization policy.`),T.unauthorized(e,t);let o=fe.get(t,il),i;o?.policyInstance?i=o.policyInstance:this.options.policyName?i={name:this.options.policyName}:i={name:"api-auth"};let a=this.options.userSubPropertyPath&&e.user?ct(e.user,this.options.userSubPropertyPath,"userSubPropertyPath"):e.user.sub,c={identityContext:o?.identityContext??{type:"IDENTITY_TYPE_SUB",identity:a},resourceContext:o?.resourceContext??{object_type:"endpoint",object_id:`${this.options.serviceName}:${e.method}:${t.route.path}`,relation:"can_invoke"},policyContext:o?.policyContext??{decisions:["allowed"],path:"rebac.check"},policyInstance:i};try{t.log.debug("Aserto Request",c);let u=await j.fetch(this.authorizationUrl,{headers:{"Content-Type":"application/json","Aserto-Tenant-ID":this.options.tenantId,Authorization:`basic ${this.options.authorizerApiKey}`},method:"POST",body:JSON.stringify(c)});if(u.status!==200){let d=`Error calling Aserto service. Status: ${u.status}`;try{d=(await u.json()).message}catch{}return t.log.error(`${this.policyType} '${this.policyName}' - ${d}`),u.status>=400&&u.status<500?r(d):T.internalServerError(e,t)}let l=await u.json();return t.log.debug("Aserto Response",l),l.decisions?.[0].is?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,l),r("The request was not authorized."))}catch(u){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling Aserto service`,u),T.internalServerError(e,t)}}};import{createRemoteJWKSet as Jf,jwtVerify as al}from"jose";import{createLocalJWKSet as Wf}from"jose";var Js=class{constructor(e,t,r){this.cache=t;if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this.url=new URL(e.href),this.options={agent:r?.agent,headers:r?.headers},this.timeoutDuration=typeof r?.timeoutDuration=="number"?r?.timeoutDuration:5e3,this.cooldownDuration=typeof r?.cooldownDuration=="number"?r?.cooldownDuration:3e4,this.cacheMaxAge=typeof r?.cacheMaxAge=="number"?r?.cacheMaxAge:6e5}static{s(this,"RemoteJWKSet")}url;timeoutDuration;cooldownDuration;cacheMaxAge;jwksTimestamp;pendingFetch;options;local;coolingDown(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cooldownDuration:!1}fresh(){return typeof this.jwksTimestamp=="number"?Date.now()<this.jwksTimestamp+this.cacheMaxAge:!1}async getKey(e,t){(!this.local||!this.fresh())&&await this.reload();try{return await this.local(e,t)}catch(r){if(r instanceof Ks&&this.coolingDown()===!1)return await this.reload(),this.local(e,t);throw r}}async reload(){this.pendingFetch&&(this.pendingFetch=void 0);let e=new Headers(this.options.headers);e.has("User-Agent")||(e.set("User-Agent",y.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Wf(t),this.jwksTimestamp=Date.now(),this.pendingFetch=void 0}).catch(t=>{throw this.pendingFetch=void 0,t}),await this.pendingFetch}async fetchJwks(e,t,r){let o=await this.cache.get(this.url.href);if(o)return o;let i,a,c=!1;typeof AbortController=="function"&&(i=new AbortController,a=setTimeout(()=>{c=!0,i.abort()},t));let u=await j.fetch(e.href,{signal:i?i.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw c?new Qs("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),u.status!==200)throw new Cn("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await u.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new Cn("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function sl(n,e,t){let r=new Js(n,e,t);return async(o,i)=>r.getKey(o,i)}s(sl,"createRemoteJWKSet");var Cn=class extends k{static{s(this,"JWKSError")}},Ks=class extends Cn{static{s(this,"JWKSNoMatchingKey")}},Qs=class extends Cn{static{s(this,"JWKSTimeout")}};var bo={},Kf=s((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new f("Invalid State - jwkUrl not set");if(!bo[r.jwkUrl]){let i=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(i=r.useExperimentalInMemoryCache),i){let a=await ge(n,void 0,r),c=new me(a,e);bo[r.jwkUrl]=sl(new URL(r.jwkUrl),c,r.headers?{headers:r.headers}:void 0)}else bo[r.jwkUrl]=Jf(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await al(t,bo[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Qf=s(async(n,e)=>{let t;if(e.secret===void 0)throw new f("secretVerifier requires secret to be defined");if(typeof e.secret=="string"){let i=new TextEncoder().encode(e.secret);t=new Uint8Array(i)}else t=e.secret;let{payload:r}=await al(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),Me=s(async(n,e,t,r)=>{g("policy.inbound.open-id-jwt-auth");let o=t.authHeader??"Authorization",i=n.headers.get(o),a="bearer ",c=s(h=>T.unauthorized(n,e,{detail:h}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new f(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?Kf(r,e):Qf,d=await s(async()=>{if(!i)return c("No authorization header");if(i.toLowerCase().indexOf(a)!==0)return c("Invalid bearer token format for authorization header");let h=i.substring(a.length);if(!h||h.length===0)return c("No bearer token on authorization header");try{return await u(h,t)}catch(w){let b=new URL(n.url);return"code"in w&&w.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${b.pathname} `,w):e.log.warn(`Invalid token on: ${n.method} ${b.pathname}`,w),c("Invalid token")}},"getJwtOrRejectedResponse")();if(d instanceof Response)return t.allowUnauthenticatedRequests===!0?n:d;let p=t.subPropertyName??"sub",m=d[p];return m?(n.user={sub:m,data:d},n):c(`Token is not valid, no '${p}' property found.`)},"OpenIdJwtInboundPolicy");var Yf=s(async(n,e,t,r)=>(g("policy.inbound.auth0-jwt-auth"),Me(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var cl=new Map;function Xf(n){let e=[],t=0;for(;t<n.length;){if(n[t]==="."){t++;continue}if(n[t]==="["){for(t++;t<n.length&&/\s/.test(n[t]);)t++;let r=n[t];if(r!=='"'&&r!=="'"){for(;t<n.length&&n[t]!=="]";)t++;t++;continue}t++;let o=t;for(;t<n.length&&n[t]!==r;)t++;let i=n.substring(o,t);for(e.push(i),t++;t<n.length&&/\s/.test(n[t]);)t++;n[t]==="]"&&t++}else{let r=t;for(;t<n.length&&n[t]!=="."&&n[t]!=="[";)t++;let o=n.substring(r,t).trim();o.length>0&&e.push(o)}}return e}s(Xf,"parsePropertyPath");function wo(n,e){let t="$authzen-prop(";if(!n.startsWith(t)||!n.endsWith(")"))return n;let r=n.slice(t.length,-1),o=cl.get(r);o||(o=Xf(r),cl.set(r,o));let i=e;for(let a of o){if(i==null)return;typeof i.get=="function"?i=i.get(a):i=i[a]}return i}s(wo,"evaluateAuthzenProp");var ul=Symbol("AUTHZEN_CONTEXT_DATA_52a5cf22-d922-4673-9815-6dc3d49071d9"),Ys=class n extends ye{static{s(this,"AuthZenInboundPolicy")}#e;#t;constructor(e,t){if(super(e,t),te(e,t).required("authorizerHostname","string").optional("authorizerAuthorizationHeader","string").optional("subject","object").optional("resource","object").optional("action","object").optional("throwOnError","boolean"),e.subject&&!e.subject.type)throw new f(`${this.policyType} '${this.policyName}' - subject.type is required.`);if(e.subject&&!e.subject.id)throw new f(`${this.policyType} '${this.policyName}' - subject.id is required.`);if(e.resource&&!e.resource.type)throw new f(`${this.policyType} '${this.policyName}' - resource.type is required.`);if(e.resource&&!e.resource.id)throw new f(`${this.policyType} '${this.policyName}' - resource.id is required.`);if(e.action&&!e.action.name)throw new f(`${this.policyType} '${this.policyName}' - action.name is required.`);this.#e=(e.authorizerHostname.startsWith("https://")?e.authorizerHostname:`https://${e.authorizerHostname}`)+"/access/v1/evaluation";try{new URL(this.#e)}catch(r){throw new f(`${this.policyType} '${this.policyName}' - authorizerUrl '${this.#e}' is not valid
|
|
91
91
|
${r}`)}}async handler(e,t){let r=this.options.throwOnError!==!1;try{await this.#o(t);let o=this.options.debug===!0,i={subject:Object.assign({},this.options.subject),resource:Object.assign({},this.options.resource),action:Object.assign({},this.options.action)},a={request:e,context:t};i.action?.name!==void 0&&(i.action.name=wo(i.action.name,a)),i.subject?.id!==void 0&&(i.subject.id=wo(i.subject.id,a)),i.resource?.id!==void 0&&(i.resource.id=wo(i.resource.id,a)),o&&t.log.debug(`${this.policyType} '${this.policyName}' - Evaluated payload from options`,i);let c=n.getAuthorizationPayload(t);c&&Object.assign(i,c),o&&t.log.debug(`${this.policyType} '${this.policyName}' - Using context payload to override working payload`,{contextPayload:c,final:i}),this.#n(t,!i.subject?.type||!i.subject?.id,"Missing required subject type or id"),this.#n(t,!i.resource?.type||!i.resource?.id,"Missing required resource type or id"),this.#n(t,!i.action,"Missing required action");let u={"content-type":"application/json"};this.options.authorizerAuthorizationHeader&&(u.authorization=this.options.authorizerAuthorizationHeader);let l=await fetch(this.#e,{method:"POST",body:JSON.stringify(i),headers:u});if(!l.ok){let p=`${this.policyType} '${this.policyName}' - Unexpected response from PDP: ${l.status} - ${l.statusText}:
|
|
92
|
-
${await l.text()}`;if(r)throw new Error(p);return t.log.error(p),e}let d=await l.json();if(o&&t.log.debug(`${this.policyType} '${this.policyName}' - PDP response`,d),d.decision!==!0)return this.#r(e,t,d.reason)}catch(o){if(r)throw o;t.log.error(`${this.policyType} '${this.policyName}' - Error in policy: ${o}`)}return e}#n(e,t,r){if(t){let o=`${this.policyType} '${this.policyName}' - ${r}`;if(this.options.throwOnError)throw new f(o);e.log.warn(o)}}async#r(e,t,r){return T.forbidden(e,t,{detail:r})}async#o(e){if(!this.#t){let t=await ge(this.policyName,void 0,this.options);this.#t=new me(t,e)}}static setAuthorizationPayload(e,t){fe.set(e,ul,t)}static getAuthorizationPayload(e){return fe.get(e,ul)}};var Ro=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{s(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await j.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var Xs=class n extends ye{static{s(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),te(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Ro(e)}async handler(e,t){let r=s(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),i=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(i,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(i,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([c,u])=>{a.push({AttributeId:`request.params.${c}`,Value:u})}),o.searchParams.forEach((c,u)=>{a.push({AttributeId:`request.query.${u}`,Value:c})}),this.addAttributesToCategory(i,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:i,context:t});try{t.log.debug("PDP Request",i);let a=await this.pdpService.makePdpRequest(i);return t.log.debug("PDP Response",a),a.Response.every(c=>c.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),T.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let i=this.options[e];if(i){let a=[];i.forEach(c=>{c.value?a.push({AttributeId:c.attributeId,Value:c.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var eg=s(async(n,e,t)=>{g("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",i=s(l=>T.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),c=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),h=d.substring(p+1),x=t.accounts.find(b=>b.username===m&&b.password===h);return x||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return t.allowUnauthenticatedRequests?n:c;let u=c.username;return n.user={sub:u,data:c.data},n},"BasicAuthInboundPolicy");function vo(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(vo,"extractDateElements");function ll(n,e){return new Date(n,e+1,0).getDate()}s(ll,"getDaysInMonth");function ea(n,e){return n<=e?e-n:6-n+e+1}s(ea,"getDaysBetweenWeekdays");var xo=class{static{s(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:i,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!i||i.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((u,l)=>u-l),this.minutes=Array.from(t).sort((u,l)=>u-l),this.hours=Array.from(r).sort((u,l)=>u-l),this.days=Array.from(o).sort((u,l)=>u-l),this.months=Array.from(i).sort((u,l)=>u-l),this.weekdays=Array.from(a).sort((u,l)=>u-l);let c=s((u,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${u} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");c("seconds",this.seconds,{min:0,max:59}),c("minutes",this.minutes,{min:0,max:59}),c("hours",this.hours,{min:0,max:23}),c("days",this.days,{min:1,max:31}),c("months",this.months,{min:0,max:11}),c("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(u=>u).reverse(),minutes:this.minutes.map(u=>u).reverse(),hours:this.hours.map(u=>u).reverse(),days:this.days.map(u=>u).reverse(),months:this.months.map(u=>u).reverse(),weekdays:this.weekdays.map(u=>u).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let i=this.findAllowedSecond(e,t.second);if(i!==void 0)return{hour:r,minute:o,second:i};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let i=ll(t,r),a=this.days.length!==31,c=this.weekdays.length!==7;if(!a&&!c)return o>i?e==="next"?void 0:i:o;let u;a&&(u=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),u!==void 0&&u>i&&(u=void 0));let l;if(c){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(m=>m>=d)??this.weekdays[0]:this.reversed.weekdays.find(m=>m<=d)??this.reversed.weekdays[0];if(p!==void 0){let m=e==="next"?ea(d,p):ea(p,d);l=e==="next"?o+m:o-m,(l>i||l<1)&&(l=void 0)}}if(u!==void 0&&l!==void 0)return e==="next"?Math.min(u,l):Math.max(u,l);if(u!==void 0)return u;if(l!==void 0)return l}getNextDate(e=new Date){let t=vo(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let i=this.months.length*5;for(let a=0;a<i;a++){let c=r+Math.floor((o+a)/this.months.length),u=this.months[(o+a)%this.months.length],l=c===t.year&&u===t.month,d=this.findAllowedDayInMonth("next",c,u,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let m=this.findAllowedTime("next",t);if(m!==void 0)return new Date(c,u,d,m.hour,m.minute,m.second);d=this.findAllowedDayInMonth("next",c,u,d+1),p=!1}if(d!==void 0&&!p)return new Date(c,u,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=vo(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let i=this.reversed.months.length*5;for(let a=0;a<i;a++){let c=r-Math.floor((o+a)/this.reversed.months.length),u=this.reversed.months[(o+a)%this.reversed.months.length],l=c===t.year&&u===t.month,d=this.findAllowedDayInMonth("prev",c,u,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let m=this.findAllowedTime("prev",t);if(m!==void 0)return new Date(c,u,d,m.hour,m.minute,m.second);d>1&&(d=this.findAllowedDayInMonth("prev",c,u,d-1),p=!1)}if(d!==void 0&&!p)return new Date(c,u,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:i,month:a,weekday:c}=vo(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(i)!==-1||this.weekdays.indexOf(c)!==-1:this.days.indexOf(i)!==-1&&this.weekdays.indexOf(c)!==-1}};var tg={min:0,max:59},ng={min:0,max:59},rg={min:0,max:23},og={min:1,max:31},ig={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},sg={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},ag={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function rn(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{rn(d,e).forEach(m=>t.add(m))}),t;let o=s(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),i=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(i===null)return t.add(o(n)),t;let a=i[1]==="*"?e.min:o(i[3]),c=i[1]==="*"?e.max:o(i[4]);if(a>c)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${c}).`);let u=i[6],l=1;if(u!==void 0){if(l=parseInt(u,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${u} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${u} to be greater than 0.`)}for(let d=a;d<=c;d=d+l)t.add(d);return t}s(rn,"parseElement");function ta(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=ag[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],i=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],c=e.length===6?e[5]:e[4];return new xo({seconds:rn(t,tg),minutes:rn(r,ng),hours:rn(o,rg),days:rn(i,og),months:new Set(Array.from(rn(a,ig)).map(u=>u-1)),weekdays:new Set(Array.from(rn(c,sg)).map(u=>u%7))})}s(ta,"parseCronExpression");var na=class extends ye{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),te(e,t).optional("problem","object"),e.problem&&te(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new f(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[ta(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>ta(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(i=>i.matchDate(r))){let i=T.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return T.format(i,e,t)}return e}};var cg=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function ug(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(ug,"digestMessage");var lg=s(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await ug(JSON.stringify(r)),i=new URL(n.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let c=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",n.method);let u=`${i.origin}${i.pathname}?${a}`;return new Request(u,{method:c?"GET":n.method})},"createCacheKeyRequest");async function dg(n,e,t,r){g("policy.inbound.caching");let o=await ge(r,t.cacheId,t),i=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await lg(n,t),u=await i.match(c);return u||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let m=t?.expirationSecondsTtl??60,h=new Response(p.body,p);cg.forEach(x=>h.headers.delete(x)),h.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(i.put(c,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}s(dg,"CachingInboundPolicy");var pg=s(async(n,e,t,r)=>{if(g("policy.inbound.change-method"),!t.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new ue(n,{method:t.method})},"ChangeMethodInboundPolicy");var mg=s(async(n,e,t)=>{g("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let c=n.headers.get(a);c&&o.set(a,c)}),new ue(n,{headers:o})},"ClearHeadersInboundPolicy");var fg=s(async(n,e,t,r)=>{g("policy.outbound.clear-headers");let o=[...r.exclude??[]],i=new Headers;return o.forEach(c=>{let u=n.headers.get(c);u&&i.set(c,u)}),new Response(n.body,{headers:i,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var gg=s(async(n,e,t,r)=>{g("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",Me(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var hg=s(async(n,e,t,r)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return Me(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Po=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},ra=class extends Po{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},oa=class extends Po{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function yg(n,e){if(Pc(n))throw new ra(e)}s(yg,"throwIfUndefinedOrNull");function dl(n,e){if(yg(n,e),!qe(n))throw new oa(e,"string")}s(dl,"throwIfNotString");var ia=class{static{s(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let o=Math.floor(t*60),i=Date.now()+o*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:i}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:i});let c=this.keyValueStore.get(e);return Promise.resolve({count:c.value,ttlSeconds:Math.round((c.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,r){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}},bg=500,sa=class{constructor(e){this.clientUrl=e}static{s(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:t,method:r,requestId:o}){dl(e,"url");let i=new AbortController;setTimeout(()=>{i.abort()},bg);let a,c=new Headers({"content-type":"application/json"});Xe(c,o);try{a=await j.fetch(`${this.clientUrl}${e}`,{method:r,body:t,signal:i.signal,headers:c})}catch(l){throw console.error("Rate limit service timed out",l),new ae("Rate limiting service failed.",{cause:l})}let u=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return u;throw a.status===401?new ae("Rate limiting service failed with 401: Unauthorized"):new ae(`Rate limiting service failed with (${a.status})`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,r){let o=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:r})}async getQuota(e,t){let r=await nn(e);return await this.fetch({url:`/quota/${r}`,method:"GET",requestId:t})}async setQuota(e,t,r){let o=await nn(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(t),requestId:r})}},On;function Lt(n,e){let{redisURL:t,authApiJWT:r}=y.instance;if(On)return On;if(!r)return e.info("Using in-memory rate limit client for local development."),On=new ia,On;if(!qe(t))throw new ae(`RateLimitClient used in policy '${n}' - rate limit service not configured`);if(!qe(r))throw new ae(`RateLimitClient used in policy '${n}' - rate limit service not configured`);return On=new sa(t),On}s(Lt,"getRateLimitClient");var wg=s(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function An(n,e){return{function:Pg(e,"RateLimitInboundPolicy",n),user:vg,ip:Rg,all:xg}[e.rateLimitBy??"ip"]}s(An,"getRateLimitByFunctions");var Rg=s(async n=>({key:`ip-${wg(n)}`}),"getIP"),vg=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),xg=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function Pg(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new f(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new f(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new f(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new f(`${e} '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,a,c)=>{let u=await r(i,a,c);if(!u||typeof u!="object"){let l=`${e} '${c}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in u)){let l=`${e} '${c}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,u),new k(l)}if(typeof u.key!="string"){let l=`${e} '${c}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof u.key}'`;throw a.log.error(l),new k(l)}return u},"outerFunction")}s(Pg,"wrapUserFunction");var _n="Retry-After";var pl=Ce("zuplo:policies:ComplexRateLimitInboundPolicy"),aa=Symbol("complex-rate-limit-counters"),ca=class n extends ye{static{s(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=fe.get(e,aa)??{};Object.assign(r,t),fe.set(e,aa,t)}static getIncrements(e){return fe.get(e,aa)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),te(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&te(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new f(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=ne.getLogger(t),i=Lt(this.policyName,o),a=s((u,l)=>{if(this.options.throwOnFailure)throw new ae(u,{cause:l});o.error(u,l)},"throwOrLog"),c=s((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[_n]=l.toString()),T.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await An(this.policyName,this.options)(e,t,this.policyName),d=y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),m=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let P=n.getIncrements(t);pl(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(P)}`);let N=Object.entries(p).map(([B])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${B}`,ttlSeconds:m,increment:P[B]??0})),A=i.multiIncrement(N,t.requestId);t.waitUntil(A),await A}catch(P){a(P.message,P)}});let h=Object.entries(p).map(([P,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${P}`,ttlSeconds:m,limit:N})),x=await i.multiCount(h,t.requestId);return Ig(x,h).length>0?c(this.options.headerMode??"retry-after",m):e}catch(u){return a(u.message,u),e}finally{let u=Date.now()-r;pl(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${u}ms`)}}};function Ig(n,e){let t=[];for(let r of n){let o=e.find(i=>i.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}s(Ig,"findOverLimits");var Eg=s(async(n,e,t,r)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=Ie.instance,i=Yn(t.policies,o?.routeData.policies);return Pi(i)(n,e)},"CompositeInboundPolicy");var Tg=s(async(n,e,t,r,o)=>{if(g("policy.outbound.composite"),!r.policies||r.policies.length===0)throw new f(`CompositeOutboundPolicy '${o}' must have valid policies defined`);let i=Ie.instance,a=Xn(r.policies,i?.routeData.policies);return Ii(a)(n,e,t)},"CompositeOutboundPolicy");var Sg=s(async(n,e,t,r)=>{g("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return T.unauthorized(n,e,{detail:"No authorization header"});let i=Cg(o);if(!i)return T.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ge(r,void 0,t),c=new me(a,e),u=await c.get(i);if(!u){let l=await j.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)u=d,c.put(i,u,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${u}`),n},"CurityPhantomTokenInboundPolicy");function Cg(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(Cg,"getToken");var Og=s(async(n,e,t,r)=>(g("policy.inbound.firebase-jwt-auth"),te(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Me(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Ag=s(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",i=n.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(n.headers);return u.set("content-type","application/json"),u.delete("content-length"),new ue(n,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");var kn="__unknown__",_g=s(async(n,e,t,r)=>{g("policy.inbound.geo-filter");let o={allow:{countries:Nn(t.allow?.countries,"allow.countries",r),regionCodes:Nn(t.allow?.regionCodes,"allow.regionCode",r),asns:Nn(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Nn(t.block?.countries,"block.countries",r),regionCodes:Nn(t.block?.regionCodes,"block.regionCode",r),asns:Nn(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??kn,a=e.incomingRequestProperties.regionCode?.toLowerCase()??kn,c=e.incomingRequestProperties.asn?.toString()??kn,u=o.ignoreUnknown&&i===kn,l=o.ignoreUnknown&&a===kn,d=o.ignoreUnknown&&c===kn,p=o.allow.countries,m=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(i)&&!u||m.length>0&&!m.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return Ln(n,e,r,i,a,c);let x=o.block.countries,b=o.block.regionCodes,P=o.block.asns;return x.length>0&&x.includes(i)&&!u||b.length>0&&b.includes(a)&&!l||P.length>0&&P.includes(c)&&!d?Ln(n,e,r,i,a,c):n},"GeoFilterInboundPolicy");function Ln(n,e,t,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),T.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(Ln,"blockedResponse");function Nn(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new f(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}s(Nn,"toLowerStringArray");var kg=s(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(c=>i.includes(c)),"scopeChecker")(r,t.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var Lg=s(async(n,e,t,r)=>{g("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return ua(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return ua(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(c=>{o[c].content&&Object.keys(o[c].content).forEach(l=>{let d=o[c].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:c,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(c=>!(t.responsePrefixFilter&&!c.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&c.contentName!==t.contentType||t.exampleName&&c.exampleName!==t.exampleName)),t.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return ml(a[c])}else return a.length>0?ml(a[0]):ua(r,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function ml(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}s(ml,"generateResponse");var ua=s((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return T.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var Ng="Incoming",Mg={logRequestBody:!0,logResponseBody:!0};function fl(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(fl,"headersToObject");function gl(){return new Date().toISOString()}s(gl,"timestamp");var la=new WeakMap,Dg={};function Zg(n,e){let t=la.get(n);t||(t=Dg);let r=Object.assign({...t},e);la.set(n,r)}s(Zg,"setMoesifContext");async function hl(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}s(hl,"readBody");var qg={},da;function yl(){if(!da)throw new k("Invalid State - no _lastLogger");return da}s(yl,"getLastLogger");function $g(n){let e=qg[n];return e||(e=new ie("moesif-inbound",100,async t=>{let r=JSON.stringify(t);yl().debug("posting",r);let o=await j.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||yl().error({status:o.status,body:await o.text()})})),e}s($g,"getDispatcher");async function Ug(n,e,t,r){g("policy.inbound.moesif-analytics"),da=e.log;let o=gl(),i=Object.assign(Mg,t);if(!i.applicationId)throw new f(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await hl(n,e):void 0;return e.addResponseSendingFinalHook(async(c,u)=>{let l=$g(i.applicationId),d=n.headers.get("true-client-ip"),p=la.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:fl(n.headers)},h=i.logResponseBody?await hl(c,e):void 0,x={time:gl(),status:c.status,headers:fl(c.headers),body:h},b={request:m,response:x,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Ng};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}s(Ug,"MoesifInboundPolicy");async function bl(n,e,t,r){let o=ne.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=y.instance,c;try{let l=await j.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)c=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let u=c&&c.data&&c.data.length>0?c.data:void 0;return u&&u.length>1?u.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:u&&u[0]}s(bl,"loadSubscription");async function wl(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=y.instance,c=ne.getLogger(n);try{let u=await j.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!u.ok){let l=await u.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${u.status} - ${d}`),c.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${u.status} - ${d}`)}}catch(u){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),c.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,u)}}s(wl,"consumeSubcriptionQuotas");var Hg=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Io(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new f(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof f?new f(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}s(Io,"validateMeters");function Rl(n,e){if(n)try{if(n.length===0)throw new f("Must set valid subscription statuses");let t=ut(n),r=[];for(let o of t)Hg.has(o)||r.push(o);if(r.length>0)throw new f(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof f?new f(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}s(Rl,"parseAllowedSubscriptionStatuses");function vl(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}s(vl,"compareMeters");var pa=class extends ye{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return fe.get(e,Bn)}static setMeters(e,t){Io(t,"setMeters");let r=fe.get(e,Gn)??{};Object.assign(r,t),fe.set(e,Gn,r)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){te(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=vt(this.options.meterOnStatusCodes),i=fe.get(t,Gn),a={...this.options.meters,...i};Io(a,this.policyName);let c=this.options.allowRequestsWithoutSubscription??!1,u=Rl(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,P,N)=>{let A=fe.get(N,Bn);if((this.options.allowRequestsWithoutSubscription??!1)&&!A){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Se.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new f(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let $=fe.get(N,Gn),G={...this.options.meters,...$};if(Io(G,this.policyName),o.includes(b.status)&&A&&G){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${A.id}' with meters '${JSON.stringify(G)} on response status '${b.status}'`);let{metersInSubscription:O,metersNotInSubscription:F}=vl(A.meters,G);if(F&&Object.keys(F).length>0){let Y=Object.keys(F);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${Y}'`)}await wl(N,A.id,this.policyName,this.options.bucketId,O)}});let l=e.user;if(!l)return c?e:T.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Se.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new f(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await bl(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),c?e:T.unauthorized(e,t,{detail:"No valid subscription found"});if(!u.includes(p.status)&&!c)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),T.unauthorized(e,t,{detail:"No valid subscription found"});u.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),fe.set(t,Bn,p));let m=fe.get(t,Bn);if(!m)return c?e:(t.log.warn("Subscription is not available for user"),T.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),T.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let x=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(x.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${x.join(", ")}`),T.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${x.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};async function Eo(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let r=await Oe({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let i=await r.text();e.log.error(`Error getting token from identity provider. Status: ${r.status}`,i)}catch{}throw new k("Error getting token from identity provider.")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}s(Eo,"getClientCredentialsAccessToken");var Mn=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{s(this,"OpenFGAError")}},To=class{static{s(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new f("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let i=new Headers(r.headers||{});i.set("Content-Type","application/json"),i.set("Accept","application/json"),i.set("User-Agent",y.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,c=new Request(a,{method:t,headers:i,body:o?JSON.stringify(o):void 0}),u=await j.fetch(c);if(u.status!==200){let l;try{l=await u.json()}catch{}throw!l||!l.code||!l.message?new Mn("unknown",`Unknown error. Status: ${u.status}`):new Mn(l.code,l.message)}return u.json()}};function Rr(n,e,t){!n[e]&&t&&(n[e]=t)}s(Rr,"setHeaderIfNotSet");var xl="X-OpenFGA-Client-Method",Pl="X-OpenFGA-Client-Bulk-Request-Id",vr=class extends To{static{s(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return Rr(r,xl,"BatchCheck"),Rr(r,Pl,crypto.randomUUID()),{responses:await Promise.all(e.map(async i=>this.check(i,Object.assign({},t,r)).then(a=>(a._request=i,a)).catch(a=>{if(a instanceof Mn)throw a;return{allowed:void 0,error:a,_request:i}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:i,contextualTuples:a,context:c}=e,{headers:u={}}=t;if(Rr(u,xl,"ListRelations"),Rr(u,Pl,crypto.randomUUID()),!i?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(i.map(p=>({user:r,relation:p,object:o,contextualTuples:a,context:c})),Object.assign({},t,u)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var Il=Symbol("openfga-authz-context-data"),Dn=class extends ye{static{s(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];fe.set(e,Il,r)}constructor(e,t){if(super(e,t),te(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new f(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")te(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")te(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")te(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new f(`${this.policyType} '${this.policyName}' - The 'credentials.method' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new vr({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await ge(this.policyName,void 0,this.options);this.cache=new me(a,t)}let r=s(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=fe.get(t,Il);if(!o||o.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let i=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:i});return t.log.debug("OpenFGA Response",a),a.responses.every(c=>c.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),T.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new ae(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let i=await Eo({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",i.access_token,i.expires_in),{Authorization:`Bearer ${i.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var El=["us1","eu1","au1"],ma=class extends Dn{static{s(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!El.includes(e.region))throw new f(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${El.join(", ")}.`);let r={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(r,t),g("policy.inbound.oktafga-authz")}};var Fg=s(async(n,e,t,r)=>(g("policy.inbound.okta-jwt-auth"),Me(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var fa=class extends Dn{static{s(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as jg}from"jose";var ga,zg=s(async(n,e,t,r)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!ga)try{ga=await jg(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Me(n,e,{issuer:t.authUrl,secret:ga,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ha="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",Tl="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var ya=class n extends ye{static{s(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let r=this.options.debug??!1;t.log.debug({debug:r}),te(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let o=ne.getLogger(t);try{let i=Bg(this.options,this.policyName),a=i.functions.getAnchorDate(e,t,this.policyName),c=i.functions.getQuotaDetail(e,t,this.policyName),[u,l]=await Promise.all([a,c]),d=Gg(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=Lt(this.policyName,o),m=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,m),r&&t.log.debug("QuotaInboundPolicy: quotaResult",m),u&&new Date(m.anchorDate).getTime()!==u.getTime()&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${u}') did not match the stored, immutable anchorDate ('${m.anchorDate}')`);let h=Object.assign({},i.defaultAllowances);Object.assign(h,l.allowances);let x=[],b="";if(Object.entries(h).forEach(([P,N])=>{r&&(b+=`${P} - allowed: ${N} value: ${m.meters[P]??0}
|
|
93
|
-
`),(m.meters[P]??0)>=N&&x.push(P)}),r&&t.log.debug("QuotaInboundPolicy: debugTable",b),x.length>0)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${x.join(", ")}'`});t.addResponseSendingFinalHook(async(P,N,A)=>{if(r&&A.log.debug(`QuotaInboundPolicy: backend response - ${P.status}: ${P.statusText}`),!i.quotaOnStatusCodes.includes(P.status))return;let B=fe.get(A,ha),$={config:{period:i.period,anchorDate:u?.toISOString()??""},increments:B};r&&A.log.debug("QuotaInboundPolicy: setQuotaDetails",$);let G=p.setQuota(d,$,A.requestId);A.waitUntil(G)})}catch(i){o.error(i),t.log.error(i)}return e}static setMeters(e,t){let r=fe.get(e,ha)??{};Object.assign(r,t),fe.set(e,ha,r)}static getUsage(e,t){let r=fe.get(e,`${Tl}-${t}`);if(r===void 0)throw new k(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return r}static#e(e,t,r){fe.set(e,`${Tl}-${t}`,r)}};function Bg(n,e){let t=s(async i=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${i.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),r=s(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new f(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new f(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);r=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:vt(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:r}}}s(Bg,"validateAndParseOptions");function Gg(n,e){return encodeURIComponent(`${e}-${n}`)}s(Gg,"processKey");var Sl=Ce("zuplo:policies:RateLimitInboundPolicy"),Cl=s(async(n,e,t,r)=>{let o=ne.getLogger(e),i=s((G,O)=>{let F={};return(!G||G==="retry-after")&&(F[_n]=O.toString()),T.tooManyRequests(n,e,void 0,F)},"rateLimited"),c=await An(r,t)(n,e,r),u=c.key,l=c.requestsAllowed??t.requestsAllowed,d=c.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",m=Lt(r,o),x=`rate-limit${y.instance.isTestMode?y.instance.build.BUILD_ID:""}/${r}/${u}`,b=await ge(r,void 0,t),P=new me(b,e),N=m.getCountAndUpdateExpiry(x,d,e.requestId),A;s(async()=>{let G=await N;if(G.count>l){let O=Date.now()+G.ttlSeconds*1e3;P.put(x,O,G.ttlSeconds),Sl(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${x}' (async mode)`),A=i(p,G.ttlSeconds)}},"asyncCheck")();let $=await P.get(x);if($!==void 0&&$>Date.now()){Sl(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${x}' (async mode)`);let G=Math.round(($-Date.now())/1e3);return i(p,G)}return e.addResponseSendingHook(async G=>A??G),n},"AsyncRateLimitInboundPolicyImpl");function ba(n,e){if(n===null)throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: null`);if(n==="")throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: empty string`);if(typeof n=="number")return n;if(typeof n!="number"){let t=Number(n);if(isNaN(t)||!Number.isInteger(t))throw new Error(`RateLimitInboundPolicy - Invalid ${e} value not of type integer: ${n}`);return t}throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: ${n}`)}s(ba,"convertToNumber");var Ol=Ce("zuplo:policies:RateLimitInboundPolicy"),Vg="strict",Al=s(async(n,e,t,r)=>{if(g("policy.inbound.rate-limit"),(t.mode??Vg)==="async")return Cl(n,e,t,r);let i=Date.now(),a=ne.getLogger(e),c=s((l,d)=>{if(t.throwOnFailure)throw new ae(l,{cause:d});a.error(l,d)},"throwOrLog"),u=s((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[_n]=d.toString()),T.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await An(r,t)(n,e,r),p=d.key,m=ba(d.requestsAllowed??t.requestsAllowed,"requestsAllowed"),h=ba(d.timeWindowMinutes??t.timeWindowMinutes,"timeWindowMinutes"),x=t.headerMode??"retry-after",b=Lt(r,a),N=`rate-limit${y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:""}/${r}/${p}`,A=await b.getCountAndUpdateExpiry(N,h,e.requestId);return A.count>m?(Ol(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${N}' (strict mode)`),u(x,A.ttlSeconds)):n}catch(l){return c(l.message,l),n}finally{let l=Date.now()-i;Ol(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var wa;function _l(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(_l,"headersToNameValuePairs");function Wg(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(Wg,"queryToNameValueParis");function Jg(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(Jg,"parseIntOrUndefined");var kl={};async function Kg(n,e,t,r){g("policy.inbound.readme-metrics");let o=new Date,i=Date.now();return wa||(wa={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let c=t.userLabelPropertyPath&&n.user?ct(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,u=t.userEmailPropertyPath&&n.user?ct(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:y.instance.isWorkingCopy||y.instance.isLocalDevelopment,group:{label:c,email:u,id:n.user?.sub??"anonymous"},request:{log:{creator:wa,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:_l(n.headers),queryString:Wg(n.query)},response:{status:a.status,statusText:a.statusText,headers:_l(a.headers),content:{size:Jg(n.headers.get("content-length"))}}}]}}},d=kl[t.apiKey];if(!d){let p=t.apiKey;d=new ie("readme-metering-inbound-policy",10,async m=>{try{let h=t.url??"https://metrics.readme.io/request",x=await j.fetch(h,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});x.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${x.status}: '${await x.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${h.message}'`),h}}),kl[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(c){e.log.error(c)}}),n}s(Kg,"ReadmeMetricsInboundPolicy");var Qg=s(async(n,e,t,r)=>{g("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(n.headers);return o.forEach(c=>{i.delete(c)}),new ue(n,{headers:i})},"RemoveHeadersInboundPolicy");var Yg=s(async(n,e,t,r,o)=>{g("policy.outbound.remove-headers");let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return i.forEach(u=>{a.delete(u)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var Xg=s(async(n,e,t,r)=>{g("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(n.url);return o.forEach(c=>{i.searchParams.delete(c)}),new ue(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var eh=s(async(n,e,t,r)=>{g("policy.outbound.replace-string");let o=await n.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Ll=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),th=s(async(n,e,t)=>{g("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>t.maxSizeInBytes?Ll():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Ll():n},"RequestSizeLimitInboundPolicy");var Zn=s(n=>{let e=n.route.raw();return e.parameters?e.parameters:[]},"getParametersForOperation"),qn=s((n,e,t,r,o)=>{let i=[],a=!0,c=[];return n.forEach(u=>{let l=u.required||o==="path";if(l&&!e[u.name])a=!1,i.push(`Required ${o} parameter '${u.name}' not found`);else if(!(!l&&!e[u.name])){let d=Ao(t,r,o,u.name),p=Ie.instance.schemaValidator[d],m=p(e[u.name]),h=Ra(p.errors);m||(a=!1,c.push(`${o} parameter: ${u.name} : ${e[u.name]}`),i.push(`Invalid value for ${o} parameter: '${u.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:i}},"validateParameters"),Ke=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),Qe=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ye=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Ra=s(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Nl(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(h){let x=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=T.badRequest(e,n,{detail:`${x}, see errors property for more details`,errors:`${h}`});if(Qe(t.validateBody)&&Ke(n,t.logLevel??"info",x,[r],h),Ye(t.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,x=T.badRequest(e,n,{detail:h});return Qe(t.validateBody)&&Ke(n,t.logLevel??"info",h,[r],[h]),Ye(t.validateBody)?x:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=_o(n.route.path,e.method,o),c=Ie.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,x=T.badRequest(e,n,{detail:h});return Qe(t.validateBody)&&Ke(n,t.logLevel??"info",h,[r],[h]),Ye(t.validateBody)?x:void 0}if(c(r))return;let l=c.errors,d="Request body did not pass validation",p=Ra(l),m=T.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Qe(t.validateBody)&&Ke(n,t.logLevel??"info",d,[r],p),Ye(t.validateBody))return m}s(Nl,"handleBodyValidation");function Ml(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,c)=>{r[c]=a});let o=Zn(n),i=qn(o.filter(a=>a.in==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",c=T.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Qe(t.validateHeaders)&&Ke(n,t.logLevel??"info",a,i.invalidValues,i.errors),Ye(t.validateHeaders))return c}}s(Ml,"handleHeadersValidation");function Dl(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Zn(n),o=qn(r.filter(i=>i.in==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=T.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Qe(t.validatePathParameters)&&Ke(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ye(t.validatePathParameters))return a}}s(Dl,"handlePathParameterValidation");function Zl(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Zn(n),o=qn(r.filter(i=>i.in==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=T.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Qe(t.validateQueryParameters)&&Ke(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ye(t.validateQueryParameters))return a}}s(Zl,"handleQueryParameterValidation");var ql=s(async(n,e,t)=>{g("policy.inbound.request-validation");let r=Zl(e,n,t);if(r!==void 0||(r=Dl(e,n,t),r!==void 0)||(r=Ml(e,n,t),r!==void 0))return r;let o=await Nl(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),nh=ql;var rh=s(async(n,e,t,r)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new f(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let i=n.headers.get("origin");if(!i||!o.includes(i)){let a=t.failureDetail??"Forbidden";return T.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var oh=s(async(n,e,t)=>(g("policy.inbound.set-body"),new ue(n,{body:t.body})),"SetBodyInboundPolicy");var ih=s(async(n,e,t,r)=>{g("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(n.headers);return o.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!i.has(c.name)||u)&&i.set(c.name,c.value)}),new ue(n,{headers:i})},"SetHeadersInboundPolicy");var sh=s(async(n,e,t,r,o)=>{g("policy.outbound.set-headers");let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return i.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var ah=s(async(n,e,t,r)=>{g("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(n.url);return o.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!i.searchParams.has(c.name)||u)&&i.searchParams.set(c.name,c.value)}),new ue(i.toString(),n)},"SetQueryParamsInboundPolicy");var ch=s(async(n,e,t,r,o)=>{if(g("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new f(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var uh=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),lh=s(async(n,e,t,r)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await uh(t.sleepInMs),n},"SleepInboundPolicy");var dh=s(async(n,e,t,r)=>{g("policy.inbound.supabase-jwt-auth"),te(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await Me(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof ue))throw new ae("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return i;let c=n.user?.data.app_metadata;if(!c)throw new k(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?T.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var ph=s(async(n,e,t,r)=>{g("policy.inbound.upstream-azure-ad-service-auth"),te(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ge(r,void 0,t),i=new me(o,e),a=await i.get(r);if(!a){let c=await mh(t,e);i.put(r,c.access_token,c.expires_in-(t.expirationOffsetSeconds??300)),a=c.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function mh(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Oe({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new k("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}s(mh,"getAccessToken");var $l="https://accounts.google.com/o/oauth2/token",va,fh=s(async(n,e,t,r)=>{g("policy.inbound.upstream-firebase-admin-auth"),te(t,r).required("serviceAccountJson","string"),va||(va=await Le.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await ge(r,void 0,t),a=new me(i,e),c=await a.get(r);if(!c){let u=await Be({serviceAccount:va,audience:$l,payload:o}),l=await dn($l,u,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("Invalid OAuth response from Firebase");c=l.access_token,a.put(r,c,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${c}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var gh="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",hh=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],xa,yh=s(async(n,e,t,r)=>{if(g("policy.inbound.upstream-firebase-user-auth"),te(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new f(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(hh.indexOf(p)!==-1)throw new f(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}xa||(xa=await Le.init(t.serviceAccountJson));let i=t.userId;if(!i&&!t.userIdPropertyPath){if(!n.user)throw new k("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new k(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=ct(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new k(`Unable to determine user from for the policy ${r}`);let a=await ge(r,void 0,t),c=new me(a,e),u={uid:i,claims:o},l=await nn(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await Be({serviceAccount:xa,audience:gh,payload:u}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await Gc(m,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new k("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var xr=class{static{s(this,"ZuploServices")}static async getIDToken(e,t){let r=new me("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await ge("zuplo-token",void 0,t),i=await r.get(o);if(i)return i;let{authClientId:a,authClientSecret:c,developerApiUrl:u,zuploClientAuthBucketId:l}=y.instance;if(!a||!c)throw new k("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await Eo({tokenEndpointUrl:`${u}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:c,audience:t?.audience},e);return r.put(o,d.access_token,d.expires_in-300),d.access_token}};var Ul="service-account-id-token",Pa=class extends ye{static{s(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),g("policy.inbound.upstream-gcp-federated-auth"),te(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await ge(this.policyName,void 0,this.options));let r;this.options.useMemoryCacheOnly?r=new et(this.cacheName):r=new me(this.cacheName,t);let o=await r.get(Ul);if(!o){let i=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await xr.getIDToken(t,{audience:i}),c=await zc(this.normalizedWorkloadIdentityProvider,a,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!c.access_token||!c.expires_in)throw new k("Invalid token response from GCP");let u=c.access_token,l=await Bc({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:u},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new k("Invalid token response from GCP");o=l.token,r.put(Ul,u,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${o}`),e}};var Ia,bh=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-jwt"),te(t,r).required("audience","string").required("serviceAccountJson","string"),Ia||(Ia=await Le.init(t.serviceAccountJson));let o=await Be({serviceAccount:Ia,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Hl="https://www.googleapis.com/oauth2/v4/token",Ea,Fl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-service-auth"),te(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ea||(Ea=await Le.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new f("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let u=ut(t.scopes);o.scope=u.join(" ")}catch(u){throw u instanceof f?new f(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${u.message}`):u}t.audience&&(o.target_audience=`${t.audience}`);let i=await ge(r,void 0,t),a;t.useMemoryCacheOnly?a=new et(i):a=new me(i,e);let c=await a.get(r);if(!c){let u=await Be({serviceAccount:Ea,audience:Hl,payload:o}),l=await dn(Hl,u,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");c=l.id_token}else{if(!l.access_token)throw new k("Invalid token response from GCP");c=l.access_token}a.put(r,c,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${c}`),n},"UpstreamGcpServiceAuthInboundPolicyV1");var jl="https://www.googleapis.com/oauth2/v4/token",Ta,zl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-service-auth"),te(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=t.expirationOffsetSeconds??300;if(t.scopes&&t.audience)throw new f("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");let i=await ge(r,"v2",t),a;t.useMemoryCacheOnly?a=new et(i):a=new me(i,e),_e.getContextExtensions(e).addHandlerResponseHook(async(d,p,m)=>{if(d.status===403){let x=`UpstreamGcpServiceAuthInboundPolicy - Handler returned a 403 response. Error: ${d.headers.get("www-authenticate")??"unknown"}. Refreshing GCP token.`;ne.getLogger(m).error(x),m.log.error(x),await a.delete(r)}});let u=await a.get(r);return u&&u.expirationTime-o<new Date().getTime()&&(ne.getLogger(e).error(`UpstreamGcpServiceAuthInboundPolicy - Expired token returned from cache for policy ${r}`),u=void 0),u&&u.audience!==t.audience&&(ne.getLogger(e).error(`UpstreamGcpServiceAuthInboundPolicy - Token with audience ${u.audience} returned from cache for policy ${r} does not match the current audience ${t.audience}`),u=void 0),u||(u=await l()),n.headers.set("Authorization",`Bearer ${u.token}`),n;async function l(){Ta||(Ta=await Le.init(t.serviceAccountJson));let d={};if(t.scopes)try{let P=ut(t.scopes);d.scope=P.join(" ")}catch(P){throw P instanceof f?new f(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${P.message}`):P}t.audience&&(d.target_audience=`${t.audience}`);let p=await Be({serviceAccount:Ta,audience:jl,payload:d}),m=await dn(jl,p,{retries:t.tokenRetries??3,retryDelayMs:10}),h=m.expires_in??3600,x=new Date().getTime()+h*1e3;if(t.audience){if(!m.id_token)throw new k("Invalid token response from GCP");u={token:m.id_token,expirationTime:x,audience:t.audience}}else{if(!m.access_token)throw new k("Invalid token response from GCP");u={token:m.access_token,expirationTime:x,audience:void 0}}let b=h-o;if(b<=0)throw new k(`UpstreamGcpServiceAuthInboundPolicy - Token TTL is less than the expiration offset. TTL: ${b}, expiration offset: ${o}`);return a.put(r,u,b),u}s(l,"retrieveGcpServiceToken")},"UpstreamGcpServiceAuthInboundPolicyV2");var wh=s(async(n,e,t,r)=>t.version===2?await zl(n,e,t,r):await Fl(n,e,t,r),"UpstreamGcpServiceAuthInboundPolicy");var Rh=s(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return T.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(o))return n;let{errors:a}=t.validator.default;if(!a)throw new ae("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return T.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");var Bl=s(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=s((b,P)=>e(b,"name",{value:P,configurable:!0}),"__name"),o=s((b,P)=>s(function(){return P||(0,b[t(b)[0]])((P={exports:{}}).exports,P),P.exports},"__require"),"__commonJS"),i=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(b){var P={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:s(function(A,B){return B},"tagValueProcessor"),attributeValueProcessor:s(function(A,B){return B},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:s(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:s(function(A,B,$){return A},"updateTag")},N=r(function(A){return Object.assign({},P,A)},"buildOptions");b.buildOptions=N,b.defaultOptions=P}}),a=o({"node_modules/fast-xml-parser/src/util.js"(b){"use strict";var P=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",N=P+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",A="["+P+"]["+N+"]*",B=new RegExp("^"+A+"$"),$=r(function(O,F){let Y=[],V=F.exec(O);for(;V;){let S=[];S.startIndex=F.lastIndex-V[0].length;let E=V.length;for(let U=0;U<E;U++)S.push(V[U]);Y.push(S),V=F.exec(O)}return Y},"getAllMatches"),G=r(function(O){let F=B.exec(O);return!(F===null||typeof F>"u")},"isName");b.isExist=function(O){return typeof O<"u"},b.isEmptyObject=function(O){return Object.keys(O).length===0},b.merge=function(O,F,Y){if(F){let V=Object.keys(F),S=V.length;for(let E=0;E<S;E++)Y==="strict"?O[V[E]]=[F[V[E]]]:O[V[E]]=F[V[E]]}},b.getValue=function(O){return b.isExist(O)?O:""},b.isName=G,b.getAllMatches=$,b.nameRegexp=A}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(b,P){"use strict";var N=class{static{s(this,"XmlNode")}static{r(this,"XmlNode")}constructor(A){this.tagname=A,this.child=[],this[":@"]={}}add(A,B){A==="__proto__"&&(A="#__proto__"),this.child.push({[A]:B})}addChild(A){A.tagname==="__proto__"&&(A.tagname="#__proto__"),A[":@"]&&Object.keys(A[":@"]).length>0?this.child.push({[A.tagname]:A.child,":@":A[":@"]}):this.child.push({[A.tagname]:A.child})}};P.exports=N}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(b,P){var N=a();function A(S,E){let U={};if(S[E+3]==="O"&&S[E+4]==="C"&&S[E+5]==="T"&&S[E+6]==="Y"&&S[E+7]==="P"&&S[E+8]==="E"){E=E+9;let we=1,ce=!1,le=!1,je="";for(;E<S.length;E++)if(S[E]==="<"&&!le){if(ce&&G(S,E))E+=7,[entityName,val,E]=B(S,E+1),val.indexOf("&")===-1&&(U[V(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(ce&&O(S,E))E+=8;else if(ce&&F(S,E))E+=8;else if(ce&&Y(S,E))E+=9;else if($)le=!0;else throw new Error("Invalid DOCTYPE");we++,je=""}else if(S[E]===">"){if(le?S[E-1]==="-"&&S[E-2]==="-"&&(le=!1,we--):we--,we===0)break}else S[E]==="["?ce=!0:je+=S[E];if(we!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:U,i:E}}s(A,"readDocType"),r(A,"readDocType");function B(S,E){let U="";for(;E<S.length&&S[E]!=="'"&&S[E]!=='"';E++)U+=S[E];if(U=U.trim(),U.indexOf(" ")!==-1)throw new Error("External entites are not supported");let we=S[E++],ce="";for(;E<S.length&&S[E]!==we;E++)ce+=S[E];return[U,ce,E]}s(B,"readEntityExp"),r(B,"readEntityExp");function $(S,E){return S[E+1]==="!"&&S[E+2]==="-"&&S[E+3]==="-"}s($,"isComment"),r($,"isComment");function G(S,E){return S[E+1]==="!"&&S[E+2]==="E"&&S[E+3]==="N"&&S[E+4]==="T"&&S[E+5]==="I"&&S[E+6]==="T"&&S[E+7]==="Y"}s(G,"isEntity"),r(G,"isEntity");function O(S,E){return S[E+1]==="!"&&S[E+2]==="E"&&S[E+3]==="L"&&S[E+4]==="E"&&S[E+5]==="M"&&S[E+6]==="E"&&S[E+7]==="N"&&S[E+8]==="T"}s(O,"isElement"),r(O,"isElement");function F(S,E){return S[E+1]==="!"&&S[E+2]==="A"&&S[E+3]==="T"&&S[E+4]==="T"&&S[E+5]==="L"&&S[E+6]==="I"&&S[E+7]==="S"&&S[E+8]==="T"}s(F,"isAttlist"),r(F,"isAttlist");function Y(S,E){return S[E+1]==="!"&&S[E+2]==="N"&&S[E+3]==="O"&&S[E+4]==="T"&&S[E+5]==="A"&&S[E+6]==="T"&&S[E+7]==="I"&&S[E+8]==="O"&&S[E+9]==="N"}s(Y,"isNotation"),r(Y,"isNotation");function V(S){if(N.isName(S))return S;throw new Error(`Invalid entity name ${S}`)}s(V,"validateEntityName"),r(V,"validateEntityName"),P.exports=A}}),l=o({"../../node_modules/strnum/strnum.js"(b,P){var N=/^[-+]?0x[a-fA-F0-9]+$/,A=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var B={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function $(O,F={}){if(F=Object.assign({},B,F),!O||typeof O!="string")return O;let Y=O.trim();if(F.skipLike!==void 0&&F.skipLike.test(Y))return O;if(F.hex&&N.test(Y))return Number.parseInt(Y,16);{let V=A.exec(Y);if(V){let S=V[1],E=V[2],U=G(V[3]),we=V[4]||V[6];if(!F.leadingZeros&&E.length>0&&S&&Y[2]!==".")return O;if(!F.leadingZeros&&E.length>0&&!S&&Y[1]!==".")return O;{let ce=Number(Y),le=""+ce;return le.search(/[eE]/)!==-1||we?F.eNotation?ce:O:Y.indexOf(".")!==-1?le==="0"&&U===""||le===U||S&&le==="-"+U?ce:O:E?U===le||S+U===le?ce:O:Y===le||Y===S+le?ce:O}}else return O}}s($,"toNumber"),r($,"toNumber");function G(O){return O&&O.indexOf(".")!==-1&&(O=O.replace(/0+$/,""),O==="."?O="0":O[0]==="."?O="0"+O:O[O.length-1]==="."&&(O=O.substr(0,O.length-1))),O}s(G,"trimZeros"),r(G,"trimZeros"),P.exports=$}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(b,P){"use strict";var N=a(),A=c(),B=u(),$=l(),G=class{static{s(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(I){this.options=I,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:s((C,M)=>String.fromCharCode(Number.parseInt(M,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:s((C,M)=>String.fromCharCode(Number.parseInt(M,16)),"val")}},this.addExternalEntities=O,this.parseXml=E,this.parseTextData=F,this.resolveNameSpace=Y,this.buildAttributesMap=S,this.isItStopNode=le,this.replaceEntitiesValue=we,this.readStopNodeData=Q,this.saveTextToParentTag=ce,this.addChild=U}};function O(I){let C=Object.keys(I);for(let M=0;M<C.length;M++){let K=C[M];this.lastEntities[K]={regex:new RegExp("&"+K+";","g"),val:I[K]}}}s(O,"addExternalEntities"),r(O,"addExternalEntities");function F(I,C,M,K,D,q,de){if(I!==void 0&&(this.options.trimValues&&!K&&(I=I.trim()),I.length>0)){de||(I=this.replaceEntitiesValue(I));let W=this.options.tagValueProcessor(C,I,M,D,q);return W==null?I:typeof W!=typeof I||W!==I?W:this.options.trimValues?Pe(I,this.options.parseTagValue,this.options.numberParseOptions):I.trim()===I?Pe(I,this.options.parseTagValue,this.options.numberParseOptions):I}}s(F,"parseTextData"),r(F,"parseTextData");function Y(I){if(this.options.removeNSPrefix){let C=I.split(":"),M=I.charAt(0)==="/"?"/":"";if(C[0]==="xmlns")return"";C.length===2&&(I=M+C[1])}return I}s(Y,"resolveNameSpace"),r(Y,"resolveNameSpace");var V=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function S(I,C,M){if(!this.options.ignoreAttributes&&typeof I=="string"){let K=N.getAllMatches(I,V),D=K.length,q={};for(let de=0;de<D;de++){let W=this.resolveNameSpace(K[de][1]),H=K[de][4],ve=this.options.attributeNamePrefix+W;if(W.length)if(this.options.transformAttributeName&&(ve=this.options.transformAttributeName(ve)),ve==="__proto__"&&(ve="#__proto__"),H!==void 0){this.options.trimValues&&(H=H.trim()),H=this.replaceEntitiesValue(H);let he=this.options.attributeValueProcessor(W,H,C);he==null?q[ve]=H:typeof he!=typeof H||he!==H?q[ve]=he:q[ve]=Pe(H,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(q[ve]=!0)}if(!Object.keys(q).length)return;if(this.options.attributesGroupName){let de={};return de[this.options.attributesGroupName]=q,de}return q}}s(S,"buildAttributesMap"),r(S,"buildAttributesMap");var E=r(function(I){I=I.replace(/\r\n?/g,`
|
|
94
|
-
`);let C=new A("!xml"),M=C,K="",D="";for(let q=0;q<I.length;q++)if(I[q]==="<")if(I[q+1]==="/"){let W=
|
|
95
|
-
`&&
|
|
96
|
-
`||w==="\r"}s(A,"isWhiteSpace"),r(A,"isWhiteSpace");function B(w,_){let Q=_;for(;_<w.length;_++)if(w[_]=="?"||w[_]==" "){let Pe=w.substr(Q,_-Q);if(_>5&&Pe==="xml")return U("InvalidXml","XML declaration allowed only at the start of the document.",le(w,_));if(w[_]=="?"&&w[_+1]==">"){_++;break}else continue}return _}s(B,"readPI"),r(B,"readPI");function $(w,_){if(w.length>_+5&&w[_+1]==="-"&&w[_+2]==="-"){for(_+=3;_<w.length;_++)if(w[_]==="-"&&w[_+1]==="-"&&w[_+2]===">"){_+=2;break}}else if(w.length>_+8&&w[_+1]==="D"&&w[_+2]==="O"&&w[_+3]==="C"&&w[_+4]==="T"&&w[_+5]==="Y"&&w[_+6]==="P"&&w[_+7]==="E"){let Q=1;for(_+=8;_<w.length;_++)if(w[_]==="<")Q++;else if(w[_]===">"&&(Q--,Q===0))break}else if(w.length>_+9&&w[_+1]==="["&&w[_+2]==="C"&&w[_+3]==="D"&&w[_+4]==="A"&&w[_+5]==="T"&&w[_+6]==="A"&&w[_+7]==="["){for(_+=8;_<w.length;_++)if(w[_]==="]"&&w[_+1]==="]"&&w[_+2]===">"){_+=2;break}}return _}s($,"readCommentAndCDATA"),r($,"readCommentAndCDATA");var G='"',O="'";function F(w,_){let Q="",Pe="",I=!1;for(;_<w.length;_++){if(w[_]===G||w[_]===O)Pe===""?Pe=w[_]:Pe!==w[_]||(Pe="");else if(w[_]===">"&&Pe===""){I=!0;break}Q+=w[_]}return Pe!==""?!1:{value:Q,index:_,tagClosed:I}}s(F,"readAttributeStr"),r(F,"readAttributeStr");var Y=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function V(w,_){let Q=P.getAllMatches(w,Y),Pe={};for(let I=0;I<Q.length;I++){if(Q[I][1].length===0)return U("InvalidAttr","Attribute '"+Q[I][2]+"' has no space in starting.",je(Q[I]));if(Q[I][3]!==void 0&&Q[I][4]===void 0)return U("InvalidAttr","Attribute '"+Q[I][2]+"' is without value.",je(Q[I]));if(Q[I][3]===void 0&&!_.allowBooleanAttributes)return U("InvalidAttr","boolean attribute '"+Q[I][2]+"' is not allowed.",je(Q[I]));let C=Q[I][2];if(!we(C))return U("InvalidAttr","Attribute '"+C+"' is an invalid name.",je(Q[I]));if(!Pe.hasOwnProperty(C))Pe[C]=1;else return U("InvalidAttr","Attribute '"+C+"' is repeated.",je(Q[I]))}return!0}s(V,"validateAttributeString"),r(V,"validateAttributeString");function S(w,_){let Q=/\d/;for(w[_]==="x"&&(_++,Q=/[\da-fA-F]/);_<w.length;_++){if(w[_]===";")return _;if(!w[_].match(Q))break}return-1}s(S,"validateNumberAmpersand"),r(S,"validateNumberAmpersand");function E(w,_){if(_++,w[_]===";")return-1;if(w[_]==="#")return _++,S(w,_);let Q=0;for(;_<w.length;_++,Q++)if(!(w[_].match(/\w/)&&Q<20)){if(w[_]===";")break;return-1}return _}s(E,"validateAmpersand"),r(E,"validateAmpersand");function U(w,_,Q){return{err:{code:w,msg:_,line:Q.line||Q,col:Q.col}}}s(U,"getErrorObject"),r(U,"getErrorObject");function we(w){return P.isName(w)}s(we,"validateAttrName"),r(we,"validateAttrName");function ce(w){return P.isName(w)}s(ce,"validateTagName"),r(ce,"validateTagName");function le(w,_){let Q=w.substring(0,_).split(/\r?\n/);return{line:Q.length,col:Q[Q.length-1].length+1}}s(le,"getLineNumberForPosition"),r(le,"getLineNumberForPosition");function je(w){return w.startIndex+w[1].length}s(je,"getPositionFromMatch"),r(je,"getPositionFromMatch")}}),h=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(b,P){var{buildOptions:N}=i(),A=d(),{prettify:B}=p(),$=m(),G=class{static{s(this,"XMLParser")}static{r(this,"XMLParser")}constructor(O){this.externalEntities={},this.options=N(O)}parse(O,F){if(typeof O!="string")if(O.toString)O=O.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(F){F===!0&&(F={});let S=$.validate(O,F);if(S!==!0)throw Error(`${S.err.msg}:${S.err.line}:${S.err.col}`)}let Y=new A(this.options);Y.addExternalEntities(this.externalEntities);let V=Y.parseXml(O);return this.options.preserveOrder||V===void 0?V:B(V,this.options)}addEntity(O,F){if(F.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(O.indexOf("&")!==-1||O.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(F==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[O]=F}};P.exports=G}});let x=h();return new x(n)},"getXmlParser");var Sa=class extends Pt{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),g("policy.outbound.xml-to-json"),te(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?vt(e.parseOnStatusCodes):void 0,this.parser=Bl({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let c=await e.text();o=this.parser.parse(c)}catch(c){let u=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(u,c),new k(u)}let i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:i})}};var Ca=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new ae(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var Gl=10,Vl=3e4,yr=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,t){if(typeof t=="number"){let r=t;this.#n=r*1e3,this.#o=Vl,this.#r=Gl}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:Vl,this.#r=Gl}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#c(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#c(e);if(t)return this.#u(e),t;if(this.#a(e))try{await vh(()=>this.#c(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#c(e);if(r)return r}catch{}return this.#l(e)}#u(e){if(!this.#a(e)){let t=this.#l(e);It().waitUntil(t)}}async#l(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new f(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function vh(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new f(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}s(vh,"waitUntilTrue");var Oa=["sha-1","sha-256","sha-384","sha-512"],So=class{static{s(this,"BaseCryptoBeta")}};var Aa=class extends So{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(g("runtime.crypto-beta"),!Oa.includes(e.toLowerCase()))throw new k(`Algorithm ${e} is not supported. Try using ${Oa.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(c=>c.toString(16).padStart(2,"0")).join("")}};export{fs as AWSLoggingPlugin,Ls as AkamaiApiSecurityPlugin,zf as AmberfloMeteringInboundPolicy,Gs as AmberfloMeteringPolicy,Vf as ApiAuthKeyInboundPolicy,Vs as ApiKeyInboundPolicy,Ws as AsertoAuthZInboundPolicy,Ss as AuditLogDataStaxProvider,Cs as AuditLogPlugin,Yf as Auth0JwtInboundPolicy,Ys as AuthZenInboundPolicy,Sp as AwsLambdaHandlerExtensions,Xs as AxiomaticsAuthZInboundPolicy,Ds as AzureBlobPlugin,Zs as AzureEventHubsRequestLoggerPlugin,br as BackgroundDispatcher,yr as BackgroundLoader,eg as BasicAuthInboundPolicy,Al as BasicRateLimitInboundPolicy,ie as BatchDispatch,na as BrownoutInboundPolicy,dg as CachingInboundPolicy,pg as ChangeMethodInboundPolicy,mg as ClearHeadersInboundPolicy,fg as ClearHeadersOutboundPolicy,gg as ClerkJwtInboundPolicy,hg as CognitoJwtInboundPolicy,ca as ComplexRateLimitInboundPolicy,Eg as CompositeInboundPolicy,Tg as CompositeOutboundPolicy,f as ConfigurationError,ci as ContentTypes,fe as ContextData,Aa as CryptoBeta,Sg as CurityPhantomTokenInboundPolicy,Mi as DataDogLoggingPlugin,ws as DataDogMetricsPlugin,rs as DynaTraceLoggingPlugin,xs as DynatraceMetricsPlugin,Og as FirebaseJwtInboundPolicy,Ag as FormDataToJsonInboundPolicy,_g as GeoFilterInboundPolicy,Ai as GoogleCloudLoggingPlugin,$i as Handler,T as HttpProblems,Ur as HttpStatusCode,qs as HydrolixRequestLoggerPlugin,ye as InboundPolicy,kg as JWTScopeValidationInboundPolicy,as as LokiLoggingPlugin,pn as LookupResult,me as MemoryZoneReadThroughCache,Lg as MockApiInboundPolicy,Ug as MoesifInboundPolicy,pa as MonetizationInboundPolicy,is as NewRelicLoggingPlugin,Es as NewRelicMetricsPlugin,ma as OktaFGAAuthZInboundPolicy,Fg as OktaJwtInboundPolicy,fa as OpenFGAAuthZInboundPolicy,Me as OpenIdJwtInboundPolicy,Pt as OutboundPolicy,Dt as ProblemResponseFormatter,zg as PropelAuthJwtInboundPolicy,ya as QuotaInboundPolicy,Al as RateLimitInboundPolicy,Kg as ReadmeMetricsInboundPolicy,Qg as RemoveHeadersInboundPolicy,Yg as RemoveHeadersOutboundPolicy,Xg as RemoveQueryParamsInboundPolicy,eh as ReplaceStringOutboundPolicy,$s as RequestLoggerPlugin,th as RequestSizeLimitInboundPolicy,ql as RequestValidationInboundPolicy,rh as RequireOriginInboundPolicy,Jn as ResponseSendingEvent,Kn as ResponseSentEvent,k as RuntimeError,Lr as SYSTEM_LOGGER,nh as SchemaBasedRequestValidation,lt as SemanticAttributes,Ca as ServiceProviderImpl,oh as SetBodyInboundPolicy,ih as SetHeadersInboundPolicy,sh as SetHeadersOutboundPolicy,ah as SetQueryParamsInboundPolicy,ch as SetStatusOutboundPolicy,lh as SleepInboundPolicy,hs as SplunkLoggingPlugin,Go as StreamingZoneCache,el as StripeMonetizationPlugin,wr as StripeWebhookVerificationInboundPolicy,ls as SumoLogicLoggingPlugin,dh as SupabaseJwtInboundPolicy,bt as SystemRouteName,Vn as TelemetryPlugin,ph as UpstreamAzureAdServiceAuthInboundPolicy,fh as UpstreamFirebaseAdminAuthInboundPolicy,yh as UpstreamFirebaseUserAuthInboundPolicy,Pa as UpstreamGcpFederatedAuthInboundPolicy,bh as UpstreamGcpJwtInboundPolicy,wh as UpstreamGcpServiceAuthInboundPolicy,ps as VMWareLogInsightLoggingPlugin,Rh as ValidateJsonSchemaInbound,Sa as XmlToJsonOutboundPolicy,$n as ZoneCache,ue as ZuploRequest,xr as ZuploServices,Rd as apiServices,Cp as awsLambdaHandler,_f as defaultGenerateHydrolixEntry,Se as environment,Ao as getIdForParameterSchema,Ql as getIdForRefSchema,_o as getIdForRequestBodySchema,Kl as getRawOperationDataIdentifierName,di as httpStatuses,uf as mcpServerHandler,Dp as openApiSpecHandler,qp as redirectHandler,Yl as sanitizedIdentifierName,ui as serialize,Zg as setMoesifContext,g as trackFeature,Hp as urlForwardHandler,jp as urlRewriteHandler,zp as webSocketHandler,Bp as webSocketPipelineHandler,$p as zuploServiceProxy};
|
|
92
|
+
${await l.text()}`;if(r)throw new Error(p);return t.log.error(p),e}let d=await l.json();if(o&&t.log.debug(`${this.policyType} '${this.policyName}' - PDP response`,d),d.decision!==!0)return this.#r(e,t,d.reason)}catch(o){if(r)throw o;t.log.error(`${this.policyType} '${this.policyName}' - Error in policy: ${o}`)}return e}#n(e,t,r){if(t){let o=`${this.policyType} '${this.policyName}' - ${r}`;if(this.options.throwOnError)throw new f(o);e.log.warn(o)}}async#r(e,t,r){return T.forbidden(e,t,{detail:r})}async#o(e){if(!this.#t){let t=await ge(this.policyName,void 0,this.options);this.#t=new me(t,e)}}static setAuthorizationPayload(e,t){fe.set(e,ul,t)}static getAuthorizationPayload(e){return fe.get(e,ul)}};var Ro=class{constructor(e){this.options=e;this.authHeader=`Basic ${btoa(e.pdpUsername+":"+e.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",e.pdpUrl).toString()}static{s(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(e){let t=await j.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(e),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!t.ok)throw new Error(`Request to PDP service failed with response status ${t.status}.`);return await t.json()}};var Xs=class n extends ye{static{s(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static#e;static setAuthAttributes(e,t){n.#e||(n.#e=new WeakMap),n.#e.set(e,{Request:t})}constructor(e,t){super(e,t),g("policy.inbound.axiomatics-authz"),te(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Ro(e)}async handler(e,t){let r=s(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=new URL(e.url),i=n.#e?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1&&e.user){let a=[{AttributeId:"request.user.sub",Value:e.user.sub}];this.addAttributesToCategory(i,"AccessSubject",a)}if(this.options.includeDefaultActionAttributes!==!1){let a=[{AttributeId:"request.method",Value:e.method}];this.addAttributesToCategory(i,"Action",a)}if(this.options.includeDefaultResourceAttributes!==!1){let a=[];a.push({AttributeId:"request.protocol",Value:o.protocol.substring(0,o.protocol.length-1)}),a.push({AttributeId:"request.host",Value:o.host}),a.push({AttributeId:"request.pathname",Value:o.pathname}),Object.entries(e.params).forEach(([c,u])=>{a.push({AttributeId:`request.params.${c}`,Value:u})}),o.searchParams.forEach((c,u)=>{a.push({AttributeId:`request.query.${u}`,Value:c})}),this.addAttributesToCategory(i,"Resource",a)}this.populateOptionAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:i,context:t}),this.populateOptionAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:i,context:t});try{t.log.debug("PDP Request",i);let a=await this.pdpService.makePdpRequest(i);return t.log.debug("PDP Response",a),a.Response.every(c=>c.Decision==="Permit")?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling PDP service`,a),T.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let i=this.options[e];if(i){let a=[];i.forEach(c=>{c.value?a.push({AttributeId:c.attributeId,Value:c.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),this.addAttributesToCategory(r,t,a)}}addAttributesToCategory(e,t,r){e.Request[t]||(e.Request[t]=[]),e.Request[t].length===0?e.Request[t].push({Attribute:[]}):e.Request[t][0].Attribute=e.Request[t][0].Attribute??[],e.Request[t][0].Attribute.push(...r)}};var eg=s(async(n,e,t)=>{g("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",i=s(l=>T.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),c=await s(async()=>{if(!r)return await i("No Authorization header");if(r.toLowerCase().indexOf(o)!==0)return await i("Invalid Basic token format for Authorization header");let l=r.substring(o.length);if(!l||l.length===0)return await i("No username:password provided");let d=atob(l).normalize(),p=d.indexOf(":");if(p===-1||/[\0-\x1F\x7F]/.test(d))return await i("Invalid basic token value - see https://tools.ietf.org/html/rfc5234#appendix-B.1");let m=d.substring(0,p),h=d.substring(p+1),w=t.accounts.find(b=>b.username===m&&b.password===h);return w||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(c instanceof Response)return t.allowUnauthenticatedRequests?n:c;let u=c.username;return n.user={sub:u,data:c.data},n},"BasicAuthInboundPolicy");function vo(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(vo,"extractDateElements");function ll(n,e){return new Date(n,e+1,0).getDate()}s(ll,"getDaysInMonth");function ea(n,e){return n<=e?e-n:6-n+e+1}s(ea,"getDaysBetweenWeekdays");var xo=class{static{s(this,"Cron")}seconds;minutes;hours;days;months;weekdays;reversed;constructor({seconds:e,minutes:t,hours:r,days:o,months:i,weekdays:a}){if(!e||e.size===0)throw new Error("There must be at least one allowed second.");if(!t||t.size===0)throw new Error("There must be at least one allowed minute.");if(!r||r.size===0)throw new Error("There must be at least one allowed hour.");if(!i||i.size===0)throw new Error("There must be at least one allowed month.");if((!a||a.size===0)&&(!o||o.size===0))throw new Error("There must be at least one allowed day or weekday.");this.seconds=Array.from(e).sort((u,l)=>u-l),this.minutes=Array.from(t).sort((u,l)=>u-l),this.hours=Array.from(r).sort((u,l)=>u-l),this.days=Array.from(o).sort((u,l)=>u-l),this.months=Array.from(i).sort((u,l)=>u-l),this.weekdays=Array.from(a).sort((u,l)=>u-l);let c=s((u,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${u} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");c("seconds",this.seconds,{min:0,max:59}),c("minutes",this.minutes,{min:0,max:59}),c("hours",this.hours,{min:0,max:23}),c("days",this.days,{min:1,max:31}),c("months",this.months,{min:0,max:11}),c("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(u=>u).reverse(),minutes:this.minutes.map(u=>u).reverse(),hours:this.hours.map(u=>u).reverse(),days:this.days.map(u=>u).reverse(),months:this.months.map(u=>u).reverse(),weekdays:this.weekdays.map(u=>u).reverse()}}findAllowedHour(e,t){return e==="next"?this.hours.find(r=>r>=t):this.reversed.hours.find(r=>r<=t)}findAllowedMinute(e,t){return e==="next"?this.minutes.find(r=>r>=t):this.reversed.minutes.find(r=>r<=t)}findAllowedSecond(e,t){return e==="next"?this.seconds.find(r=>r>t):this.reversed.seconds.find(r=>r<t)}findAllowedTime(e,t){let r=this.findAllowedHour(e,t.hour);if(r!==void 0)if(r===t.hour){let o=this.findAllowedMinute(e,t.minute);if(o!==void 0)if(o===t.minute){let i=this.findAllowedSecond(e,t.second);if(i!==void 0)return{hour:r,minute:o,second:i};if(o=this.findAllowedMinute(e,e==="next"?t.minute+1:t.minute-1),o!==void 0)return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:o,second:e==="next"?this.seconds[0]:this.reversed.seconds[0]};if(r=this.findAllowedHour(e,e==="next"?t.hour+1:t.hour-1),r!==void 0)return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}else return{hour:r,minute:e==="next"?this.minutes[0]:this.reversed.minutes[0],second:e==="next"?this.seconds[0]:this.reversed.seconds[0]}}findAllowedDayInMonth(e,t,r,o){if(o<1)throw new Error("startDay must not be smaller than 1.");let i=ll(t,r),a=this.days.length!==31,c=this.weekdays.length!==7;if(!a&&!c)return o>i?e==="next"?void 0:i:o;let u;a&&(u=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),u!==void 0&&u>i&&(u=void 0));let l;if(c){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(m=>m>=d)??this.weekdays[0]:this.reversed.weekdays.find(m=>m<=d)??this.reversed.weekdays[0];if(p!==void 0){let m=e==="next"?ea(d,p):ea(p,d);l=e==="next"?o+m:o-m,(l>i||l<1)&&(l=void 0)}}if(u!==void 0&&l!==void 0)return e==="next"?Math.min(u,l):Math.max(u,l);if(u!==void 0)return u;if(l!==void 0)return l}getNextDate(e=new Date){let t=vo(e),r=t.year,o=this.months.findIndex(a=>a>=t.month);o===-1&&(o=0,r++);let i=this.months.length*5;for(let a=0;a<i;a++){let c=r+Math.floor((o+a)/this.months.length),u=this.months[(o+a)%this.months.length],l=c===t.year&&u===t.month,d=this.findAllowedDayInMonth("next",c,u,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let m=this.findAllowedTime("next",t);if(m!==void 0)return new Date(c,u,d,m.hour,m.minute,m.second);d=this.findAllowedDayInMonth("next",c,u,d+1),p=!1}if(d!==void 0&&!p)return new Date(c,u,d,this.hours[0],this.minutes[0],this.seconds[0])}throw new Error("No valid next date was found.")}getNextDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getNextDate(o??t),r.push(o);return r}*getNextDatesIterator(e,t){let r;for(;;){if(r=this.getNextDate(e),e=r,t&&t.getTime()<r.getTime())return;yield r}}getPrevDate(e=new Date){let t=vo(e),r=t.year,o=this.reversed.months.findIndex(a=>a<=t.month);o===-1&&(o=0,r--);let i=this.reversed.months.length*5;for(let a=0;a<i;a++){let c=r-Math.floor((o+a)/this.reversed.months.length),u=this.reversed.months[(o+a)%this.reversed.months.length],l=c===t.year&&u===t.month,d=this.findAllowedDayInMonth("prev",c,u,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let m=this.findAllowedTime("prev",t);if(m!==void 0)return new Date(c,u,d,m.hour,m.minute,m.second);d>1&&(d=this.findAllowedDayInMonth("prev",c,u,d-1),p=!1)}if(d!==void 0&&!p)return new Date(c,u,d,this.reversed.hours[0],this.reversed.minutes[0],this.reversed.seconds[0])}throw new Error("No valid previous date was found.")}getPrevDates(e,t){let r=[],o;for(let i=0;i<e;i++)o=this.getPrevDate(o??t),r.push(o);return r}*getPrevDatesIterator(e,t){let r;for(;;){if(r=this.getPrevDate(e),e=r,t&&t.getTime()>r.getTime())return;yield r}}matchDate(e){let{second:t,minute:r,hour:o,day:i,month:a,weekday:c}=vo(e);return this.seconds.indexOf(t)===-1||this.minutes.indexOf(r)===-1||this.hours.indexOf(o)===-1||this.months.indexOf(a)===-1?!1:this.days.length!==31&&this.weekdays.length!==7?this.days.indexOf(i)!==-1||this.weekdays.indexOf(c)!==-1:this.days.indexOf(i)!==-1&&this.weekdays.indexOf(c)!==-1}};var tg={min:0,max:59},ng={min:0,max:59},rg={min:0,max:23},og={min:1,max:31},ig={min:1,max:12,aliases:{jan:"1",feb:"2",mar:"3",apr:"4",may:"5",jun:"6",jul:"7",aug:"8",sep:"9",oct:"10",nov:"11",dec:"12"}},sg={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},ag={"@yearly":"0 0 1 1 *","@annually":"0 0 1 1 *","@monthly":"0 0 1 1 *","@weekly":"0 0 * * 0","@daily":"0 0 * * *","@hourly":"0 * * * *","@minutely":"* * * * *"};function rn(n,e){let t=new Set;if(n==="*"){for(let d=e.min;d<=e.max;d=d+1)t.add(d);return t}let r=n.split(",");if(r.length>1)return r.forEach(d=>{rn(d,e).forEach(m=>t.add(m))}),t;let o=s(d=>{d=e.aliases?.[d.toLowerCase()]??d;let p=parseInt(d,10);if(Number.isNaN(p))throw new Error(`Failed to parse ${n}: ${d} is NaN.`);if(p<e.min||p>e.max)throw new Error(`Failed to parse ${n}: ${d} is outside of constraint range of ${e.min} - ${e.max}.`);return p},"parseSingleElement"),i=/^((([0-9a-zA-Z]+)-([0-9a-zA-Z]+))|\*)(\/([0-9]+))?$/.exec(n);if(i===null)return t.add(o(n)),t;let a=i[1]==="*"?e.min:o(i[3]),c=i[1]==="*"?e.max:o(i[4]);if(a>c)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${c}).`);let u=i[6],l=1;if(u!==void 0){if(l=parseInt(u,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${u} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${u} to be greater than 0.`)}for(let d=a;d<=c;d=d+l)t.add(d);return t}s(rn,"parseElement");function ta(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=ag[n.toLowerCase()]??n;let e=n.split(" ");if(e.length<5||e.length>6)throw new Error("Invalid cron expression: expected 5 or 6 elements.");let t=e.length===6?e[0]:"0",r=e.length===6?e[1]:e[0],o=e.length===6?e[2]:e[1],i=e.length===6?e[3]:e[2],a=e.length===6?e[4]:e[3],c=e.length===6?e[5]:e[4];return new xo({seconds:rn(t,tg),minutes:rn(r,ng),hours:rn(o,rg),days:rn(i,og),months:new Set(Array.from(rn(a,ig)).map(u=>u-1)),weekdays:new Set(Array.from(rn(c,sg)).map(u=>u%7))})}s(ta,"parseCronExpression");var na=class extends ye{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),te(e,t).optional("problem","object"),e.problem&&te(e.problem,t,"policy","problem").optional("detail","string").optional("status","string").optional("title","string"),typeof e.cronSchedule!="string"&&!(typeof e.cronSchedule=="object"&&Array.isArray(e.cronSchedule)&&!e.cronSchedule.some(r=>typeof r!="string")))throw new f(`Value of 'cronSchedule' on policy '${t}' must be of type string or string[]. Received type ${typeof e.cronSchedule}.`);typeof this.options.cronSchedule=="string"?this.crons=[ta(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>ta(r))}async handler(e,t){let r=new Date;if(r.setSeconds(0),r.setMilliseconds(0),this.crons.some(i=>i.matchDate(r))){let i=T.getProblemFromStatus(this.options.problem?.status??400,{detail:"This API is performing a scheduled brownout in advance of its pending deprecation. Please upgrade to a later version.",...this.options.problem});return T.format(i,e,t)}return e}};var cg=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function ug(n){let e=new TextEncoder().encode(n),t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t)).map(i=>i.toString(16).padStart(2,"0")).join("")}s(ug,"digestMessage");var lg=s(async(n,e)=>{let t=[...e.dangerouslyIgnoreAuthorizationHeader===!0?[]:["authorization"],...e.headers??[]],r=[];for(let[d,p]of n.headers.entries())t.includes(d)&&r.push({key:d.toLowerCase(),value:p});r.sort((d,p)=>d.key.localeCompare(p.key));let o=await ug(JSON.stringify(r)),i=new URL(n.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let c=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";c&&a.set("_z-original-method",n.method);let u=`${i.origin}${i.pathname}?${a}`;return new Request(u,{method:c?"GET":n.method})},"createCacheKeyRequest");async function dg(n,e,t,r){g("policy.inbound.caching");let o=await ge(r,t.cacheId,t),i=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],c=await lg(n,t),u=await i.match(c);return u||(e.addEventListener("responseSent",l=>{try{let d=t.statusCodes??[200,206,301,302,303,404,410],p=l.response.clone();if(!d.includes(p.status)||!a.includes(n.method.toUpperCase()))return;let m=t?.expirationSecondsTtl??60,h=new Response(p.body,p);cg.forEach(w=>h.headers.delete(w)),h.headers.set("cache-control",`s-maxage=${m}`),e.waitUntil(i.put(c,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}s(dg,"CachingInboundPolicy");var pg=s(async(n,e,t,r)=>{if(g("policy.inbound.change-method"),!t.method)throw new f(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new ue(n,{method:t.method})},"ChangeMethodInboundPolicy");var mg=s(async(n,e,t)=>{g("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let c=n.headers.get(a);c&&o.set(a,c)}),new ue(n,{headers:o})},"ClearHeadersInboundPolicy");var fg=s(async(n,e,t,r)=>{g("policy.outbound.clear-headers");let o=[...r.exclude??[]],i=new Headers;return o.forEach(c=>{let u=n.headers.get(c);u&&i.set(c,u)}),new Response(n.body,{headers:i,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var gg=s(async(n,e,t,r)=>{g("policy.inbound.clerk-jwt-auth");let o=new URL(t.frontendApiUrl.startsWith("https://")||t.frontendApiUrl.startsWith("http://")?t.frontendApiUrl:`https://${t.frontendApiUrl}`),i=new URL(o);return i.pathname="/.well-known/jwks.json",Me(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var hg=s(async(n,e,t,r)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new f("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new f("region must be set in the options for CognitoJwtInboundPolicy");return Me(n,e,{issuer:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}`,jwkUrl:`https://cognito-idp.${t.region}.amazonaws.com/${t.userPoolId}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"CognitoJwtInboundPolicy");var Po=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},ra=class extends Po{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},oa=class extends Po{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function yg(n,e){if(Pc(n))throw new ra(e)}s(yg,"throwIfUndefinedOrNull");function dl(n,e){if(yg(n,e),!qe(n))throw new oa(e,"string")}s(dl,"throwIfNotString");var ia=class{static{s(this,"InMemoryRateLimitClient")}keyValueStore;constructor(){this.keyValueStore=new Map}getCountAndUpdateExpiry(e,t){let o=Math.floor(t*60),i=Date.now()+o*1e3,a=this.keyValueStore.get(e);a?Date.now()>a.expiresAt?this.keyValueStore.set(e,{value:1,expiresAt:i}):this.keyValueStore.set(e,{value:a.value+1,expiresAt:a.expiresAt}):this.keyValueStore.set(e,{value:1,expiresAt:i});let c=this.keyValueStore.get(e);return Promise.resolve({count:c.value,ttlSeconds:Math.round((c.expiresAt-Date.now())/1e3)})}multiIncrement(e,t){throw new Error("In memory complex rate limits are not currently supported.")}multiCount(e,t){throw new Error("In memory complex rate limits are not currently supported.")}setQuota(e,t,r){throw new Error("In memory quotas are not currently supported.")}getQuota(e,t){throw new Error("In memory quotas are not currently supported.")}},bg=500,sa=class{constructor(e){this.clientUrl=e}static{s(this,"RemoteRateLimitClient")}static instance;async fetch({url:e,body:t,method:r,requestId:o}){dl(e,"url");let i=new AbortController;setTimeout(()=>{i.abort()},bg);let a,c=new Headers({"content-type":"application/json"});Xe(c,o);try{a=await j.fetch(`${this.clientUrl}${e}`,{method:r,body:t,signal:i.signal,headers:c})}catch(l){throw console.error("Rate limit service timed out",l),new ae("Rate limiting service failed.",{cause:l})}let u=a.headers.get("Content-Type")?.includes("application/json")?await a.json():await a.text();if(a.ok)return u;throw a.status===401?new ae("Rate limiting service failed with 401: Unauthorized"):new ae(`Rate limiting service failed with (${a.status})`)}async multiCount(e,t){return(await this.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async multiIncrement(e,t){return(await this.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:e}),requestId:t})).data}async getCountAndUpdateExpiry(e,t,r){let o=Math.floor(t*60);return await this.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:e}),requestId:r})}async getQuota(e,t){let r=await nn(e);return await this.fetch({url:`/quota/${r}`,method:"GET",requestId:t})}async setQuota(e,t,r){let o=await nn(e);await this.fetch({url:`/quota/${o}`,method:"POST",body:JSON.stringify(t),requestId:r})}},On;function Lt(n,e){let{redisURL:t,authApiJWT:r}=y.instance;if(On)return On;if(!r)return e.info("Using in-memory rate limit client for local development."),On=new ia,On;if(!qe(t))throw new ae(`RateLimitClient used in policy '${n}' - rate limit service not configured`);if(!qe(r))throw new ae(`RateLimitClient used in policy '${n}' - rate limit service not configured`);return On=new sa(t),On}s(Lt,"getRateLimitClient");var wg=s(n=>{let e=n.headers.get("x-real-ip")??n.headers.get("true-client-ip")??n.headers.get("cf-connecting-ip");if(e)return e;let t=n.headers.get("x-forwarded-for");return t?t.split(",")[0]:"127.0.0.1"},"getRealIP");function An(n,e){return{function:Pg(e,"RateLimitInboundPolicy",n),user:vg,ip:Rg,all:xg}[e.rateLimitBy??"ip"]}s(An,"getRateLimitByFunctions");var Rg=s(async n=>({key:`ip-${wg(n)}`}),"getIP"),vg=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),xg=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll");function Pg(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new f(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new f(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new f(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(r=n.identifier.module[n.identifier.export],!r||typeof r!="function")throw new f(`${e} '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,a,c)=>{let u=await r(i,a,c);if(!u||typeof u!="object"){let l=`${e} '${c}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new k(l)}if(!("key"in u)){let l=`${e} '${c}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,u),new k(l)}if(typeof u.key!="string"){let l=`${e} '${c}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof u.key}'`;throw a.log.error(l),new k(l)}return u},"outerFunction")}s(Pg,"wrapUserFunction");var _n="Retry-After";var pl=Ce("zuplo:policies:ComplexRateLimitInboundPolicy"),aa=Symbol("complex-rate-limit-counters"),ca=class n extends ye{static{s(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=fe.get(e,aa)??{};Object.assign(r,t),fe.set(e,aa,t)}static getIncrements(e){return fe.get(e,aa)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),te(e,t).required("rateLimitBy","string").required("timeWindowMinutes","number").required("limits","object").optional("headerMode","string").optional("throwOnFailure","boolean").optional("mode","string").optional("identifier","object"),e.identifier&&te(e.identifier,t,"policy","identifier").required("export","string").required("module","object");for(let[r,o]of Object.entries(e.limits))if(typeof o!="number")throw new f(`ComplexRateLimitInboundPolicy '${this.policyName}' - The value of the limits must be numbers. The limit ${r} is set to type '${typeof e}'.`)}async handler(e,t){let r=Date.now(),o=ne.getLogger(t),i=Lt(this.policyName,o),a=s((u,l)=>{if(this.options.throwOnFailure)throw new ae(u,{cause:l});o.error(u,l)},"throwOrLog"),c=s((u,l)=>{let d={};return(!u||u==="retry-after")&&(d[_n]=l.toString()),T.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await An(this.policyName,this.options)(e,t,this.policyName),d=y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:"",p=Object.assign({},this.options.limits,l.limits),m=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let P=n.getIncrements(t);pl(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(P)}`);let N=Object.entries(p).map(([B])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${B}`,ttlSeconds:m,increment:P[B]??0})),A=i.multiIncrement(N,t.requestId);t.waitUntil(A),await A}catch(P){a(P.message,P)}});let h=Object.entries(p).map(([P,N])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${P}`,ttlSeconds:m,limit:N})),w=await i.multiCount(h,t.requestId);return Ig(w,h).length>0?c(this.options.headerMode??"retry-after",m):e}catch(u){return a(u.message,u),e}finally{let u=Date.now()-r;pl(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${u}ms`)}}};function Ig(n,e){let t=[];for(let r of n){let o=e.find(i=>i.key===r.key)?.limit||0;r.count>=o&&t.push(r)}return t}s(Ig,"findOverLimits");var Eg=s(async(n,e,t,r)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new f(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=Ie.instance,i=Yn(t.policies,o?.routeData.policies);return Pi(i)(n,e)},"CompositeInboundPolicy");var Tg=s(async(n,e,t,r,o)=>{if(g("policy.outbound.composite"),!r.policies||r.policies.length===0)throw new f(`CompositeOutboundPolicy '${o}' must have valid policies defined`);let i=Ie.instance,a=Xn(r.policies,i?.routeData.policies);return Ii(a)(n,e,t)},"CompositeOutboundPolicy");var Sg=s(async(n,e,t,r)=>{g("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return T.unauthorized(n,e,{detail:"No authorization header"});let i=Cg(o);if(!i)return T.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ge(r,void 0,t),c=new me(a,e),u=await c.get(i);if(!u){let l=await j.fetch(t.introspectionUrl,{headers:{Authorization:"Basic "+btoa(`${t.clientId}:${t.clientSecret}`),Accept:"application/jwt","Content-Type":"application/x-www-form-urlencoded"},method:"POST",body:"token="+i+"&token_type_hint=access_token"}),d=await l.text();if(l.status===200)u=d,c.put(i,u,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),T.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):T.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${u}`),n},"CurityPhantomTokenInboundPolicy");function Cg(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(Cg,"getToken");var Og=s(async(n,e,t,r)=>(g("policy.inbound.firebase-jwt-auth"),te(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),Me(n,e,{issuer:`https://securetoken.google.com/${t.projectId}`,audience:t.projectId,jwkUrl:"https://www.googleapis.com/service_accounts/v1/jwk/securetoken@system.gserviceaccount.com",allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"FirebaseJwtInboundPolicy");var Ag=s(async(n,e,t)=>{g("policy.inbound.form-data-to-json");let r="application/x-www-form-urlencoded",o="multipart/form-data",i=n.headers.get("content-type")?.toLowerCase();if(!i||![o,r].includes(i))return t&&t.badRequestIfNotFormData?new Response(`Bad Request - expected content-type '${r}' or ${o}`,{status:400,statusText:"Bad Request"}):n;let a=await n.formData();if(t&&t.optionalHoneypotName&&a.get(t.optionalHoneypotName)!=="")return new Response("Bad Request",{status:400,statusText:"Bad Request"});let c={};for(let[d,p]of a)c[d]=p.toString();let u=new Headers(n.headers);return u.set("content-type","application/json"),u.delete("content-length"),new ue(n,{body:JSON.stringify(c),headers:u})},"FormDataToJsonInboundPolicy");var kn="__unknown__",_g=s(async(n,e,t,r)=>{g("policy.inbound.geo-filter");let o={allow:{countries:Nn(t.allow?.countries,"allow.countries",r),regionCodes:Nn(t.allow?.regionCodes,"allow.regionCode",r),asns:Nn(t.allow?.asns,"allow.asOrganization",r)},block:{countries:Nn(t.block?.countries,"block.countries",r),regionCodes:Nn(t.block?.regionCodes,"block.regionCode",r),asns:Nn(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??kn,a=e.incomingRequestProperties.regionCode?.toLowerCase()??kn,c=e.incomingRequestProperties.asn?.toString()??kn,u=o.ignoreUnknown&&i===kn,l=o.ignoreUnknown&&a===kn,d=o.ignoreUnknown&&c===kn,p=o.allow.countries,m=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(i)&&!u||m.length>0&&!m.includes(a)&&!l||h.length>0&&!h.includes(c)&&!d)return Ln(n,e,r,i,a,c);let w=o.block.countries,b=o.block.regionCodes,P=o.block.asns;return w.length>0&&w.includes(i)&&!u||b.length>0&&b.includes(a)&&!l||P.length>0&&P.includes(c)&&!d?Ln(n,e,r,i,a,c):n},"GeoFilterInboundPolicy");function Ln(n,e,t,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),T.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(Ln,"blockedResponse");function Nn(n,e,t){if(typeof n=="string")return n.split(",").map(r=>r.trim().toLowerCase());if(typeof n>"u")return[];if(Array.isArray(n))return n.map(r=>r.trim().toLowerCase());throw new f(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}s(Nn,"toLowerStringArray");var kg=s(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(c=>i.includes(c)),"scopeChecker")(r,t.scopes)){let i={code:"UNAUTHORIZED",help_url:"https://zup.fail/UNAUTHORIZED",message:`JWT must have all the following scopes: ${t.scopes}`};return new Response(JSON.stringify(i),{status:401,statusText:"Unauthorized",headers:{"content-type":"application/json"}})}return n},"JWTScopeValidationInboundPolicy");var Lg=s(async(n,e,t,r)=>{g("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return ua(r,n,e,"No responses defined in the OpenAPI document. Add some responses with examples to use this policy.");let i=Object.keys(o),a=[];if(i.length===0)return ua(r,n,e,"No response object defined under responses in the OpenAPI document. Add some response objects with examples to use this policy.");if(i.forEach(c=>{o[c].content&&Object.keys(o[c].content).forEach(l=>{let d=o[c].content[l].examples;d&&Object.keys(d).forEach(m=>{a.push({responseName:c,contentName:l,exampleName:m,exampleValue:d[m]})})})}),a=a.filter(c=>!(t.responsePrefixFilter&&!c.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&c.contentName!==t.contentType||t.exampleName&&c.exampleName!==t.exampleName)),t.random&&a.length>1){let c=Math.floor(Math.random()*a.length);return ml(a[c])}else return a.length>0?ml(a[0]):ua(r,n,e,"No examples matching the mocking options found in the OpenAPI document. Add examples to the OpenAPI document matching the options for this policy or change the mocking options to match the examples in the OpenAPI document.")},"MockApiInboundPolicy");function ml(n){let e=JSON.stringify(n.exampleValue,null,2),t=new Headers;switch(t.set("Content-Type",n.contentName),n.responseName){case"1XX":return new Response(e,{status:100,headers:t});case"2XX":return new Response(e,{status:200,headers:t});case"3XX":return new Response(e,{status:300,headers:t});case"4XX":return new Response(e,{status:400,headers:t});case"5XX":case"default":return new Response(e,{status:500,headers:t});default:return new Response(e,{status:Number(n.responseName),headers:t})}}s(ml,"generateResponse");var ua=s((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return T.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var Ng="Incoming",Mg={logRequestBody:!0,logResponseBody:!0};function fl(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(fl,"headersToObject");function gl(){return new Date().toISOString()}s(gl,"timestamp");var la=new WeakMap,Dg={};function Zg(n,e){let t=la.get(n);t||(t=Dg);let r=Object.assign({...t},e);la.set(n,r)}s(Zg,"setMoesifContext");async function hl(n,e){let t=n.headers.get("content-type");if(t&&t.indexOf("json")!==-1)try{return await n.clone().json()}catch(o){e.log.error(o)}let r=await n.clone().text();return e.log.debug({textBody:r}),r}s(hl,"readBody");var qg={},da;function yl(){if(!da)throw new k("Invalid State - no _lastLogger");return da}s(yl,"getLastLogger");function $g(n){let e=qg[n];return e||(e=new ie("moesif-inbound",100,async t=>{let r=JSON.stringify(t);yl().debug("posting",r);let o=await j.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||yl().error({status:o.status,body:await o.text()})})),e}s($g,"getDispatcher");async function Ug(n,e,t,r){g("policy.inbound.moesif-analytics"),da=e.log;let o=gl(),i=Object.assign(Mg,t);if(!i.applicationId)throw new f(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await hl(n,e):void 0;return e.addResponseSendingFinalHook(async(c,u)=>{let l=$g(i.applicationId),d=n.headers.get("true-client-ip"),p=la.get(e)??{},m={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:fl(n.headers)},h=i.logResponseBody?await hl(c,e):void 0,w={time:gl(),status:c.status,headers:fl(c.headers),body:h},b={request:m,response:w,user_id:p.userId??u.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Ng};l.enqueue(b),e.waitUntil(l.waitUntilFlushed())}),n}s(Ug,"MoesifInboundPolicy");async function bl(n,e,t,r){let o=ne.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=y.instance,c;try{let l=await j.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)c=await l.json();else{let d=await l.json(),p=d.detail??d.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error loading subscription. ${l.status} - ${p}`),o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription.${l.status} - ${p}`)}}catch(l){o.error(`MonetizationInboundPolicy '${t}' - Error loading subscription`,l)}let u=c&&c.data&&c.data.length>0?c.data:void 0;return u&&u.length>1?u.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:u&&u[0]}s(bl,"loadSubscription");async function wl(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=y.instance,c=ne.getLogger(n);try{let u=await j.fetch(`${a}/internal/v1/metering/${r}/subscriptions/${e}/quotas/consume`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"POST",body:JSON.stringify({meters:o})});if(!u.ok){let l=await u.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${u.status} - ${d}`),c.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${u.status} - ${d}`)}}catch(u){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),c.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,u)}}s(wl,"consumeSubcriptionQuotas");var Hg=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Io(n,e){try{let t=[];for(let r in n)typeof n[r]!="number"&&!(Number.isInteger(n[r])&&/^-?\d+$/.test(n[r].toString()))&&t.push(r);if(t.length>0)throw new f(t.length>1?`The values found in these properties are not integers : ${t.join(", ")}`:`The value in property '${t[0]}' is not an integer`)}catch(t){throw t instanceof f?new f(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}s(Io,"validateMeters");function Rl(n,e){if(n)try{if(n.length===0)throw new f("Must set valid subscription statuses");let t=ut(n),r=[];for(let o of t)Hg.has(o)||r.push(o);if(r.length>0)throw new f(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof f?new f(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}s(Rl,"parseAllowedSubscriptionStatuses");function vl(n,e){let t={},r={};for(let o in e)n.hasOwnProperty(o)?t[o]=e[o]:r[o]=e[o];return{metersInSubscription:t,metersNotInSubscription:r}}s(vl,"compareMeters");var pa=class extends ye{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return fe.get(e,Bn)}static setMeters(e,t){Io(t,"setMeters");let r=fe.get(e,Gn)??{};Object.assign(r,t),fe.set(e,Gn,r)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){te(this.options,this.policyName).optional("allowRequestsWithoutSubscription","boolean").optional("allowRequestsOverQuota","boolean").optional("bucketId","string"),this.options.meterOnStatusCodes||(this.options.meterOnStatusCodes="200-399");let r=this.options.allowRequestsOverQuota??!1,o=vt(this.options.meterOnStatusCodes),i=fe.get(t,Gn),a={...this.options.meters,...i};Io(a,this.policyName);let c=this.options.allowRequestsWithoutSubscription??!1,u=Rl(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(b,P,N)=>{let A=fe.get(N,Bn);if((this.options.allowRequestsWithoutSubscription??!1)&&!A){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(Se.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new f(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let $=fe.get(N,Gn),G={...this.options.meters,...$};if(Io(G,this.policyName),o.includes(b.status)&&A&&G){N.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${A.id}' with meters '${JSON.stringify(G)} on response status '${b.status}'`);let{metersInSubscription:O,metersNotInSubscription:F}=vl(A.meters,G);if(F&&Object.keys(F).length>0){let Y=Object.keys(F);N.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${Y}'`)}await wl(N,A.id,this.policyName,this.options.bucketId,O)}});let l=e.user;if(!l)return c?e:T.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(Se.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=Se.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new f(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await bl(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),c?e:T.unauthorized(e,t,{detail:"No valid subscription found"});if(!u.includes(p.status)&&!c)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),T.unauthorized(e,t,{detail:"No valid subscription found"});u.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),fe.set(t,Bn,p));let m=fe.get(t,Bn);if(!m)return c?e:(t.log.warn("Subscription is not available for user"),T.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(m&&Object.keys(m.meters).length===0)return t.log.error(`Quota is not set up for subscription '${m.id}'`),T.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let w=Object.keys(a).filter(b=>!Object.keys(m.meters).includes(b));if(w.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${w.join(", ")}`),T.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${w.join(", ")}`,title:"Quota Exceeded"});for(let b of Object.keys(a))if(m.meters[b].available<=0&&!r)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${b}'`,title:"Quota Exceeded"});return e}};async function Eo(n,e){let t=new URLSearchParams({client_id:n.clientId,client_secret:n.clientSecret,grant_type:"client_credentials"});n.scope&&t.append("scope",n.scope),n.audience&&t.append("audience",n.audience);let r=await Oe({retries:n.retries?.maxRetries??3,retryDelayMs:n.retries?.delayMs??10},n.tokenEndpointUrl,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let i=await r.text();e.log.error(`Error getting token from identity provider. Status: ${r.status}`,i)}catch{}throw new k("Error getting token from identity provider.")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from identity provider is not in the expected format.")}s(Eo,"getClientCredentialsAccessToken");var Mn=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{s(this,"OpenFGAError")}},To=class{static{s(this,"BaseOpenFGAClient")}apiUrl;storeId;authorizationModelId;constructor(e){this.apiUrl=e.apiUrl,this.storeId=e.storeId,this.authorizationModelId=e.authorizationModelId}getStoreId(e={},t=!1){let r=e?.storeId||this.storeId;if(!t&&!r)throw new f("storeId is required");return r}getAuthorizationModelId(e={}){return e?.authorizationModelId||this.authorizationModelId}async get(e,t){return this.fetch(e,"GET",t)}async put(e,t,r){return this.fetch(e,"PUT",r,t)}post(e,t,r){return this.fetch(e,"POST",r,t)}async fetch(e,t,r,o){let i=new Headers(r.headers||{});i.set("Content-Type","application/json"),i.set("Accept","application/json"),i.set("User-Agent",y.instance.systemUserAgent);let a=`${this.apiUrl}${e}`,c=new Request(a,{method:t,headers:i,body:o?JSON.stringify(o):void 0}),u=await j.fetch(c);if(u.status!==200){let l;try{l=await u.json()}catch{}throw!l||!l.code||!l.message?new Mn("unknown",`Unknown error. Status: ${u.status}`):new Mn(l.code,l.message)}return u.json()}};function Rr(n,e,t){!n[e]&&t&&(n[e]=t)}s(Rr,"setHeaderIfNotSet");var xl="X-OpenFGA-Client-Method",Pl="X-OpenFGA-Client-Bulk-Request-Id",vr=class extends To{static{s(this,"OpenFGAClient")}async check(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/check`,{tuple_key:{user:e.user,relation:e.relation,object:e.object},context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]},authorization_model_id:this.getAuthorizationModelId(t)},t)}async batchCheck(e,t={}){let{headers:r={}}=t;return Rr(r,xl,"BatchCheck"),Rr(r,Pl,crypto.randomUUID()),{responses:await Promise.all(e.map(async i=>this.check(i,Object.assign({},t,r)).then(a=>(a._request=i,a)).catch(a=>{if(a instanceof Mn)throw a;return{allowed:void 0,error:a,_request:i}})))}}async expand(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/expand`,{authorization_model_id:this.getAuthorizationModelId(t),tuple_key:e},t)}async listObjects(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-objects`,{authorization_model_id:this.getAuthorizationModelId(t),user:e.user,relation:e.relation,type:e.type,context:e.context,contextual_tuples:{tuple_keys:e.contextualTuples||[]}},t)}async listRelations(e,t={}){let{user:r,object:o,relations:i,contextualTuples:a,context:c}=e,{headers:u={}}=t;if(Rr(u,xl,"ListRelations"),Rr(u,Pl,crypto.randomUUID()),!i?.length)throw new Error("When calling listRelations, at least one relation must be passed in the relations field");let l=await this.batchCheck(i.map(p=>({user:r,relation:p,object:o,contextualTuples:a,context:c})),Object.assign({},t,u)),d=l.responses.find(p=>p.error);if(d)throw d.error;return{relations:l.responses.filter(p=>p.allowed).map(p=>p._request.relation)}}async listUsers(e,t={}){return this.post(`/stores/${this.getStoreId(t)}/list-users`,{authorization_model_id:this.getAuthorizationModelId(t),relation:e.relation,object:e.object,user_filters:e.user_filters,context:e.context,contextual_tuples:e.contextualTuples||[]},t)}};var Il=Symbol("openfga-authz-context-data"),Dn=class extends ye{static{s(this,"BaseOpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];fe.set(e,Il,r)}constructor(e,t){if(super(e,t),te(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new f(`${this.policyType} '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")te(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")te(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")te(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new f(`${this.policyType} '${this.policyName}' - The 'credentials.method' option is invalid. It must be set to either 'none', 'api-token', 'client-credentials', or 'header'.`);this.authorizer=this.getAuthorizer(e.credentials),this.client=new vr({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await ge(this.policyName,void 0,this.options);this.cache=new me(a,t)}let r=s(a=>this.options.allowUnauthorizedRequests?e:T.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=fe.get(t,Il);if(!o||o.length===0)throw new k(`${this.policyType} '${this.policyName}' - No checks found in the context.`);let i=await this.authorizer(e,t);try{t.log.debug("OpenFGA checks",o);let a=await this.client.batchCheck(o,{headers:i});return t.log.debug("OpenFGA Response",a),a.responses.every(c=>c.allowed)?e:(t.log.debug(`${this.policyType} '${this.policyName}' - The request was not authorized.`,a),r("The request was not authorized."))}catch(a){return t.log.error(`${this.policyType} '${this.policyName}' - Error calling OpenFGA service`,a),T.internalServerError(e,t)}}getAuthorizer(e){if(e.method==="none")return async()=>({});if(e.method==="header")return async t=>{let r=e.headerName??"Authorization",o=t.headers.get(r);if(!o)throw new ae(`${this.policyType} '${this.policyName}' - The header '${r}' is missing.`);return{[r]:o}};if(e.method==="api-token")return async()=>({[e.headerName??"Authorization"]:`${e.headerValuePrefix??"Bearer "} ${e.token}`});if(e.method==="client-credentials")return async(t,r)=>{let o=await this.cache?.get("client_credentials_token");if(o)return{Authorization:`Bearer ${o}`};let i=await Eo({tokenEndpointUrl:e.oauthTokenEndpointUrl,clientId:e.clientId,clientSecret:e.clientSecret,audience:e.apiAudience},r);return this.cache?.put("client_credentials_token",i.access_token,i.expires_in),{Authorization:`Bearer ${i.access_token}`}};throw new k("Invalid state for credentials method is not valid. This should not happen.")}};var El=["us1","eu1","au1"],ma=class extends Dn{static{s(this,"OktaFGAAuthZInboundPolicy")}constructor(e,t){if(!El.includes(e.region))throw new f(`OktaFGAAuthZInboundPolicy '${t}' - The 'region' option is invalid. Must be one of ${El.join(", ")}.`);let r={...e,apiUrl:`https://api.${e.region}.fga.dev`,credentials:{method:"client-credentials",oauthTokenEndpointUrl:"https://fga.us.auth0.com/oauth/token",clientId:e.credentials.clientId,clientSecret:e.credentials.clientSecret,apiAudience:`https://api.${e.region}.fga.dev/`}};super(r,t),g("policy.inbound.oktafga-authz")}};var Fg=s(async(n,e,t,r)=>(g("policy.inbound.okta-jwt-auth"),Me(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");var fa=class extends Dn{static{s(this,"OpenFGAAuthZInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.openfga-authz")}};import{importSPKI as jg}from"jose";var ga,zg=s(async(n,e,t,r)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!ga)try{ga=await jg(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return Me(n,e,{issuer:t.authUrl,secret:ga,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var ha="quota-inbound-policy-f307056c-8c00-4f2c-b4ac-c0ac7d04eca0",Tl="quota-usage-2017e968-4de8-4a63-8951-1e423df0d64b";var ya=class n extends ye{static{s(this,"QuotaInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.quota")}async handler(e,t){let r=this.options.debug??!1;t.log.debug({debug:r}),te(this.options,this.policyName).required("period","string").required("quotaBy","string").optional("quotaAnchorMode","string").optional("allowances","object"),n.setMeters(t,{requests:1});let o=ne.getLogger(t);try{let i=Bg(this.options,this.policyName),a=i.functions.getAnchorDate(e,t,this.policyName),c=i.functions.getQuotaDetail(e,t,this.policyName),[u,l]=await Promise.all([a,c]),d=Gg(l.key,this.policyName);r&&t.log.debug(`QuotaInboundPolicy: key - '${d}'`);let p=Lt(this.policyName,o),m=await p.getQuota(d,t.requestId);n.#e(t,this.policyName,m),r&&t.log.debug("QuotaInboundPolicy: quotaResult",m),u&&new Date(m.anchorDate).getTime()!==u.getTime()&&t.log.warn(`QuotaInboundPolicy '${this.policyName}' provided anchorDate ('${u}') did not match the stored, immutable anchorDate ('${m.anchorDate}')`);let h=Object.assign({},i.defaultAllowances);Object.assign(h,l.allowances);let w=[],b="";if(Object.entries(h).forEach(([P,N])=>{r&&(b+=`${P} - allowed: ${N} value: ${m.meters[P]??0}
|
|
93
|
+
`),(m.meters[P]??0)>=N&&w.push(P)}),r&&t.log.debug("QuotaInboundPolicy: debugTable",b),w.length>0)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meters '${w.join(", ")}'`});t.addResponseSendingFinalHook(async(P,N,A)=>{if(r&&A.log.debug(`QuotaInboundPolicy: backend response - ${P.status}: ${P.statusText}`),!i.quotaOnStatusCodes.includes(P.status))return;let B=fe.get(A,ha),$={config:{period:i.period,anchorDate:u?.toISOString()??""},increments:B};r&&A.log.debug("QuotaInboundPolicy: setQuotaDetails",$);let G=p.setQuota(d,$,A.requestId);A.waitUntil(G)})}catch(i){o.error(i),t.log.error(i)}return e}static setMeters(e,t){let r=fe.get(e,ha)??{};Object.assign(r,t),fe.set(e,ha,r)}static getUsage(e,t){let r=fe.get(e,`${Tl}-${t}`);if(r===void 0)throw new k(`QuotaInboundPolicy.getUsage was called for policy named '${t}' but the policy itself has not yet executed.`);return r}static#e(e,t,r){fe.set(e,`${Tl}-${t}`,r)}};function Bg(n,e){let t=s(async i=>({key:`user-1385b4e8-800f-488e-b089-c197544e5801-${i.user?.sub}`,allowances:n.allowances??{}}),"getQuotaDetail"),r=s(async()=>{},"getAnchorDate");if(n.quotaBy==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getQuotaDetailExport===void 0)throw new f(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getQuotaDetailExport' is required when 'quotaBy' is 'function'`);t=n.identifier.module[n.identifier.getQuotaDetailExport]}if(n.quotaAnchorMode==="function"){if(n.identifier===void 0||n.identifier.module===void 0||n.identifier.getAnchorDateExport===void 0)throw new f(`QuotaInboundPolicy '${e}' - The property 'identifier.module' and 'identifier.getAnchorDateExport' is required when 'quotaAnchorMode' is 'function'`);r=n.identifier.module[n.identifier.getAnchorDateExport]}return{period:n.period,quotaBy:n.quotaBy??"user",quotaAnchorMode:n.quotaAnchorMode??"first-api-call",quotaOnStatusCodes:vt(n.quotaOnStatusCodes??"200-299"),defaultAllowances:Object.assign({},n.allowances),functions:{getQuotaDetail:t,getAnchorDate:r}}}s(Bg,"validateAndParseOptions");function Gg(n,e){return encodeURIComponent(`${e}-${n}`)}s(Gg,"processKey");var Sl=Ce("zuplo:policies:RateLimitInboundPolicy"),Cl=s(async(n,e,t,r)=>{let o=ne.getLogger(e),i=s((G,O)=>{let F={};return(!G||G==="retry-after")&&(F[_n]=O.toString()),T.tooManyRequests(n,e,void 0,F)},"rateLimited"),c=await An(r,t)(n,e,r),u=c.key,l=c.requestsAllowed??t.requestsAllowed,d=c.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",m=Lt(r,o),w=`rate-limit${y.instance.isTestMode?y.instance.build.BUILD_ID:""}/${r}/${u}`,b=await ge(r,void 0,t),P=new me(b,e),N=m.getCountAndUpdateExpiry(w,d,e.requestId),A;s(async()=>{let G=await N;if(G.count>l){let O=Date.now()+G.ttlSeconds*1e3;P.put(w,O,G.ttlSeconds),Sl(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${w}' (async mode)`),A=i(p,G.ttlSeconds)}},"asyncCheck")();let $=await P.get(w);if($!==void 0&&$>Date.now()){Sl(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${w}' (async mode)`);let G=Math.round(($-Date.now())/1e3);return i(p,G)}return e.addResponseSendingHook(async G=>A??G),n},"AsyncRateLimitInboundPolicyImpl");function ba(n,e){if(n===null)throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: null`);if(n==="")throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: empty string`);if(typeof n=="number")return n;if(typeof n!="number"){let t=Number(n);if(isNaN(t)||!Number.isInteger(t))throw new Error(`RateLimitInboundPolicy - Invalid ${e} value not of type integer: ${n}`);return t}throw new Error(`RateLimitInboundPolicy - Invalid ${e} value: ${n}`)}s(ba,"convertToNumber");var Ol=Ce("zuplo:policies:RateLimitInboundPolicy"),Vg="strict",Al=s(async(n,e,t,r)=>{if(g("policy.inbound.rate-limit"),(t.mode??Vg)==="async")return Cl(n,e,t,r);let i=Date.now(),a=ne.getLogger(e),c=s((l,d)=>{if(t.throwOnFailure)throw new ae(l,{cause:d});a.error(l,d)},"throwOrLog"),u=s((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[_n]=d.toString()),T.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await An(r,t)(n,e,r),p=d.key,m=ba(d.requestsAllowed??t.requestsAllowed,"requestsAllowed"),h=ba(d.timeWindowMinutes??t.timeWindowMinutes,"timeWindowMinutes"),w=t.headerMode??"retry-after",b=Lt(r,a),N=`rate-limit${y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:""}/${r}/${p}`,A=await b.getCountAndUpdateExpiry(N,h,e.requestId);return A.count>m?(Ol(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${N}' (strict mode)`),u(w,A.ttlSeconds)):n}catch(l){return c(l.message,l),n}finally{let l=Date.now()-i;Ol(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var wa;function _l(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(_l,"headersToNameValuePairs");function Wg(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(Wg,"queryToNameValueParis");function Jg(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(Jg,"parseIntOrUndefined");var kl={};async function Kg(n,e,t,r){g("policy.inbound.readme-metrics");let o=new Date,i=Date.now();return wa||(wa={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let c=t.userLabelPropertyPath&&n.user?ct(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,u=t.userEmailPropertyPath&&n.user?ct(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:y.instance.isWorkingCopy||y.instance.isLocalDevelopment,group:{label:c,email:u,id:n.user?.sub??"anonymous"},request:{log:{creator:wa,entries:[{startedDateTime:o.toISOString(),time:Date.now()-i,request:{method:n.method,url:t.useFullRequestPath?new URL(n.url).pathname:e.route.path,httpVersion:"2",headers:_l(n.headers),queryString:Wg(n.query)},response:{status:a.status,statusText:a.statusText,headers:_l(a.headers),content:{size:Jg(n.headers.get("content-length"))}}}]}}},d=kl[t.apiKey];if(!d){let p=t.apiKey;d=new ie("readme-metering-inbound-policy",10,async m=>{try{let h=t.url??"https://metrics.readme.io/request",w=await j.fetch(h,{method:"POST",body:JSON.stringify(m),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});w.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${w.status}: '${await w.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${h.message}'`),h}}),kl[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(c){e.log.error(c)}}),n}s(Kg,"ReadmeMetricsInboundPolicy");var Qg=s(async(n,e,t,r)=>{g("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(n.headers);return o.forEach(c=>{i.delete(c)}),new ue(n,{headers:i})},"RemoveHeadersInboundPolicy");var Yg=s(async(n,e,t,r,o)=>{g("policy.outbound.remove-headers");let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new f(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return i.forEach(u=>{a.delete(u)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var Xg=s(async(n,e,t,r)=>{g("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new f(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(n.url);return o.forEach(c=>{i.searchParams.delete(c)}),new ue(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var eh=s(async(n,e,t,r)=>{g("policy.outbound.replace-string");let o=await n.text(),i=r.mode==="regexp"?new RegExp(r.match,"gm"):r.match,a=o.replaceAll(i,r.replaceWith);return new Response(a,{headers:n.headers,status:n.status,statusText:n.statusText})},"ReplaceStringOutboundPolicy");var Ll=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),th=s(async(n,e,t)=>{g("policy.inbound.request-size-limit");let r=t.trustContentLengthHeader??!1;if(["GET","HEAD"].includes(n.method))return n;let o=n.headers.get("content-length"),i=o!==null?parseInt(o):void 0;return i&&!isNaN(i)&&i>t.maxSizeInBytes?Ll():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Ll():n},"RequestSizeLimitInboundPolicy");var Zn=s(n=>{let e=n.route.raw();return e.parameters?e.parameters:[]},"getParametersForOperation"),qn=s((n,e,t,r,o)=>{let i=[],a=!0,c=[];return n.forEach(u=>{let l=u.required||o==="path";if(l&&!e[u.name])a=!1,i.push(`Required ${o} parameter '${u.name}' not found`);else if(!(!l&&!e[u.name])){let d=Ao(t,r,o,u.name),p=Ie.instance.schemaValidator[d],m=p(e[u.name]),h=Ra(p.errors);m||(a=!1,c.push(`${o} parameter: ${u.name} : ${e[u.name]}`),i.push(`Invalid value for ${o} parameter: '${u.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:c,errors:i}},"validateParameters"),Ke=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),Qe=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ye=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Ra=s(n=>n?.map(e=>e.instancePath===void 0||e.instancePath===""?e.message??"Unknown validation error":e.instancePath.replace("/","")+" "+e.message)??["Unknown validation error"],"getErrorsFromValidator");async function Nl(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(h){let w=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,b=T.badRequest(e,n,{detail:`${w}, see errors property for more details`,errors:`${h}`});if(Qe(t.validateBody)&&Ke(n,t.logLevel??"info",w,[r],h),Ye(t.validateBody))return b}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,w=T.badRequest(e,n,{detail:h});return Qe(t.validateBody)&&Ke(n,t.logLevel??"info",h,[r],[h]),Ye(t.validateBody)?w:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=_o(n.route.path,e.method,o),c=Ie.instance.schemaValidator[a];if(!c){let h=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,w=T.badRequest(e,n,{detail:h});return Qe(t.validateBody)&&Ke(n,t.logLevel??"info",h,[r],[h]),Ye(t.validateBody)?w:void 0}if(c(r))return;let l=c.errors,d="Request body did not pass validation",p=Ra(l),m=T.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Qe(t.validateBody)&&Ke(n,t.logLevel??"info",d,[r],p),Ye(t.validateBody))return m}s(Nl,"handleBodyValidation");function Ml(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,c)=>{r[c]=a});let o=Zn(n),i=qn(o.filter(a=>a.in==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",c=T.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Qe(t.validateHeaders)&&Ke(n,t.logLevel??"info",a,i.invalidValues,i.errors),Ye(t.validateHeaders))return c}}s(Ml,"handleHeadersValidation");function Dl(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Zn(n),o=qn(r.filter(i=>i.in==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=T.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Qe(t.validatePathParameters)&&Ke(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ye(t.validatePathParameters))return a}}s(Dl,"handlePathParameterValidation");function Zl(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Zn(n),o=qn(r.filter(i=>i.in==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=T.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Qe(t.validateQueryParameters)&&Ke(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ye(t.validateQueryParameters))return a}}s(Zl,"handleQueryParameterValidation");var ql=s(async(n,e,t)=>{g("policy.inbound.request-validation");let r=Zl(e,n,t);if(r!==void 0||(r=Dl(e,n,t),r!==void 0)||(r=Ml(e,n,t),r!==void 0))return r;let o=await Nl(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),nh=ql;var rh=s(async(n,e,t,r)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new f(`RequireOriginInboundPolicy '${r}' configuration error - no allowed origins specified`);let o=typeof t.origins=="string"?t.origins.split(","):t.origins;o=o.map(a=>a.trim());let i=n.headers.get("origin");if(!i||!o.includes(i)){let a=t.failureDetail??"Forbidden";return T.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var oh=s(async(n,e,t)=>(g("policy.inbound.set-body"),new ue(n,{body:t.body})),"SetBodyInboundPolicy");var ih=s(async(n,e,t,r)=>{g("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(n.headers);return o.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!i.has(c.name)||u)&&i.set(c.name,c.value)}),new ue(n,{headers:i})},"SetHeadersInboundPolicy");var sh=s(async(n,e,t,r,o)=>{g("policy.outbound.set-headers");let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new f(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return i.forEach(u=>{if(!u.name||u.name.length===0)throw new f(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=u.overwrite===void 0?!0:u.overwrite;(!a.has(u.name)||l)&&a.set(u.name,u.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var ah=s(async(n,e,t,r)=>{g("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new f(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(n.url);return o.forEach(c=>{if(!c.name||c.name.length===0)throw new f(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let u=c.overwrite===void 0?!0:c.overwrite;(!i.searchParams.has(c.name)||u)&&i.searchParams.set(c.name,c.value)}),new ue(i.toString(),n)},"SetQueryParamsInboundPolicy");var ch=s(async(n,e,t,r,o)=>{if(g("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new f(`Invalid SetStatusOutboundPolicy '${o}' - status must be a valid number between 100 and 599, not '${r.status}'`);return new Response(n.body,{headers:n.headers,status:r.status,statusText:r.statusText??n.statusText})},"SetStatusOutboundPolicy");var uh=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),lh=s(async(n,e,t,r)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new f(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await uh(t.sleepInMs),n},"SleepInboundPolicy");var dh=s(async(n,e,t,r)=>{g("policy.inbound.supabase-jwt-auth"),te(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await Me(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof ue))throw new ae("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return i;let c=n.user?.data.app_metadata;if(!c)throw new k(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let u=Object.keys(a),l=[];return u.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(c[d])||l.push(d):p!==c[d]&&l.push(d)}),l.length>0?T.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var ph=s(async(n,e,t,r)=>{g("policy.inbound.upstream-azure-ad-service-auth"),te(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ge(r,void 0,t),i=new me(o,e),a=await i.get(r);if(!a){let c=await mh(t,e);i.put(r,c.access_token,c.expires_in-(t.expirationOffsetSeconds??300)),a=c.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function mh(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Oe({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new k("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}s(mh,"getAccessToken");var $l="https://accounts.google.com/o/oauth2/token",va,fh=s(async(n,e,t,r)=>{g("policy.inbound.upstream-firebase-admin-auth"),te(t,r).required("serviceAccountJson","string"),va||(va=await Le.init(t.serviceAccountJson));let o={scope:["https://www.googleapis.com/auth/cloud-platform","https://www.googleapis.com/auth/firebase.database","https://www.googleapis.com/auth/firebase.messaging","https://www.googleapis.com/auth/identitytoolkit","https://www.googleapis.com/auth/userinfo.email"].join(" ")},i=await ge(r,void 0,t),a=new me(i,e),c=await a.get(r);if(!c){let u=await Be({serviceAccount:va,audience:$l,payload:o}),l=await dn($l,u,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("Invalid OAuth response from Firebase");c=l.access_token,a.put(r,c,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${c}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var gh="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",hh=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],xa,yh=s(async(n,e,t,r)=>{if(g("policy.inbound.upstream-firebase-user-auth"),te(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new f(`Either 'userId' or 'userIdPropertyPath' options must be set on policy '${r}'.`);let o={};if(typeof t.developerClaims<"u"){for(let p in t.developerClaims)if(Object.prototype.hasOwnProperty.call(t.developerClaims,p)){if(hh.indexOf(p)!==-1)throw new f(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}xa||(xa=await Le.init(t.serviceAccountJson));let i=t.userId;if(!i&&!t.userIdPropertyPath){if(!n.user)throw new k("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new k(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=ct(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new k(`Unable to determine user from for the policy ${r}`);let a=await ge(r,void 0,t),c=new me(a,e),u={uid:i,claims:o},l=await nn(JSON.stringify(u)),d=await c.get(l);if(!d){let p=await Be({serviceAccount:xa,audience:gh,payload:u}),m=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await Gc(m,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new k("Invalid token response from Firebase");d=h.idToken,c.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var xr=class{static{s(this,"ZuploServices")}static async getIDToken(e,t){let r=new me("0c13603a-a19f-4f03-a04a-50aa393f7ffa-zuplo-tokens",e),o=await ge("zuplo-token",void 0,t),i=await r.get(o);if(i)return i;let{authClientId:a,authClientSecret:c,developerApiUrl:u,zuploClientAuthBucketId:l}=y.instance;if(!a||!c)throw new k("Zuplo service authentication is not enabled for this deployment. Contact support assistance.");let d=await Eo({tokenEndpointUrl:`${u}/v1/client-auth/${l}/oauth/token`,clientId:a,clientSecret:c,audience:t?.audience},e);return r.put(o,d.access_token,d.expires_in-300),d.access_token}};var Ul="service-account-id-token",Pa=class extends ye{static{s(this,"UpstreamGcpFederatedAuthInboundPolicy")}cacheName;normalizedWorkloadIdentityProvider;constructor(e,t){super(e,t),g("policy.inbound.upstream-gcp-federated-auth"),te(e,t).required("audience","string").required("serviceAccountEmail","string").required("workloadIdentityProvider","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number").optional("useMemoryCacheOnly","boolean").optional("tokenLifetime","number"),e.workloadIdentityProvider.startsWith("https://iam.googleapis.com/")?this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider.replace("https://iam.googleapis.com/",""):this.normalizedWorkloadIdentityProvider=e.workloadIdentityProvider}async handler(e,t){this.cacheName||(this.cacheName=await ge(this.policyName,void 0,this.options));let r;this.options.useMemoryCacheOnly?r=new et(this.cacheName):r=new me(this.cacheName,t);let o=await r.get(Ul);if(!o){let i=`https://iam.googleapis.com/${this.normalizedWorkloadIdentityProvider}`,a=await xr.getIDToken(t,{audience:i}),c=await zc(this.normalizedWorkloadIdentityProvider,a,{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!c.access_token||!c.expires_in)throw new k("Invalid token response from GCP");let u=c.access_token,l=await Bc({serviceAccountEmailOrIdentifier:this.options.serviceAccountEmail,audience:this.options.audience,accessToken:u},{retries:this.options.tokenRetries??3,retryDelayMs:10});if(!l.token)throw new k("Invalid token response from GCP");o=l.token,r.put(Ul,u,3600-(this.options.expirationOffsetSeconds??300))}return e.headers.set("Authorization",`Bearer ${o}`),e}};var Ia,bh=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-jwt"),te(t,r).required("audience","string").required("serviceAccountJson","string"),Ia||(Ia=await Le.init(t.serviceAccountJson));let o=await Be({serviceAccount:Ia,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Hl="https://www.googleapis.com/oauth2/v4/token",Ea,Fl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-service-auth"),te(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ea||(Ea=await Le.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new f("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let u=ut(t.scopes);o.scope=u.join(" ")}catch(u){throw u instanceof f?new f(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${u.message}`):u}t.audience&&(o.target_audience=`${t.audience}`);let i=await ge(r,void 0,t),a;t.useMemoryCacheOnly?a=new et(i):a=new me(i,e);let c=await a.get(r);if(!c){let u=await Be({serviceAccount:Ea,audience:Hl,payload:o}),l=await dn(Hl,u,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");c=l.id_token}else{if(!l.access_token)throw new k("Invalid token response from GCP");c=l.access_token}a.put(r,c,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${c}`),n},"UpstreamGcpServiceAuthInboundPolicyV1");var jl="https://www.googleapis.com/oauth2/v4/token",Ta,zl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-service-auth"),te(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=t.expirationOffsetSeconds??300;if(t.scopes&&t.audience)throw new f("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");let i=await ge(r,"v2",t),a;t.useMemoryCacheOnly?a=new et(i):a=new me(i,e),_e.getContextExtensions(e).addHandlerResponseHook(async(d,p,m)=>{if(d.status===403){let w=`UpstreamGcpServiceAuthInboundPolicy - Handler returned a 403 response. Error: ${d.headers.get("www-authenticate")??"unknown"}. Refreshing GCP token.`;ne.getLogger(m).error(w),m.log.error(w),await a.delete(r)}});let u=await a.get(r);return u&&u.expirationTime-o<new Date().getTime()&&(ne.getLogger(e).error(`UpstreamGcpServiceAuthInboundPolicy - Expired token returned from cache for policy ${r}`),u=void 0),u&&u.audience!==t.audience&&(ne.getLogger(e).error(`UpstreamGcpServiceAuthInboundPolicy - Token with audience ${u.audience} returned from cache for policy ${r} does not match the current audience ${t.audience}`),u=void 0),u||(u=await l()),n.headers.set("Authorization",`Bearer ${u.token}`),n;async function l(){Ta||(Ta=await Le.init(t.serviceAccountJson));let d={};if(t.scopes)try{let P=ut(t.scopes);d.scope=P.join(" ")}catch(P){throw P instanceof f?new f(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${P.message}`):P}t.audience&&(d.target_audience=`${t.audience}`);let p=await Be({serviceAccount:Ta,audience:jl,payload:d}),m=await dn(jl,p,{retries:t.tokenRetries??3,retryDelayMs:10}),h=m.expires_in??3600,w=new Date().getTime()+h*1e3;if(t.audience){if(!m.id_token)throw new k("Invalid token response from GCP");u={token:m.id_token,expirationTime:w,audience:t.audience}}else{if(!m.access_token)throw new k("Invalid token response from GCP");u={token:m.access_token,expirationTime:w,audience:void 0}}let b=h-o;if(b<=0)throw new k(`UpstreamGcpServiceAuthInboundPolicy - Token TTL is less than the expiration offset. TTL: ${b}, expiration offset: ${o}`);return a.put(r,u,b),u}s(l,"retrieveGcpServiceToken")},"UpstreamGcpServiceAuthInboundPolicyV2");var wh=s(async(n,e,t,r)=>t.version===2?await zl(n,e,t,r):await Fl(n,e,t,r),"UpstreamGcpServiceAuthInboundPolicy");var Rh=s(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return T.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator.default(o))return n;let{errors:a}=t.validator.default;if(!a)throw new ae("Invalid state - validator error object is undefined even though validation failed.");let c=a.map(u=>u.instancePath===void 0||u.instancePath===""?"Body "+u.message:u.instancePath.replace("/","")+" "+u.message);return T.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:c})},"ValidateJsonSchemaInbound");var Bl=s(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=s((b,P)=>e(b,"name",{value:P,configurable:!0}),"__name"),o=s((b,P)=>s(function(){return P||(0,b[t(b)[0]])((P={exports:{}}).exports,P),P.exports},"__require"),"__commonJS"),i=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(b){var P={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:s(function(A,B){return B},"tagValueProcessor"),attributeValueProcessor:s(function(A,B){return B},"attributeValueProcessor"),stopNodes:[],alwaysCreateTextNode:!1,isArray:s(()=>!1,"isArray"),commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:s(function(A,B,$){return A},"updateTag")},N=r(function(A){return Object.assign({},P,A)},"buildOptions");b.buildOptions=N,b.defaultOptions=P}}),a=o({"node_modules/fast-xml-parser/src/util.js"(b){"use strict";var P=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",N=P+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",A="["+P+"]["+N+"]*",B=new RegExp("^"+A+"$"),$=r(function(O,F){let Y=[],V=F.exec(O);for(;V;){let S=[];S.startIndex=F.lastIndex-V[0].length;let E=V.length;for(let U=0;U<E;U++)S.push(V[U]);Y.push(S),V=F.exec(O)}return Y},"getAllMatches"),G=r(function(O){let F=B.exec(O);return!(F===null||typeof F>"u")},"isName");b.isExist=function(O){return typeof O<"u"},b.isEmptyObject=function(O){return Object.keys(O).length===0},b.merge=function(O,F,Y){if(F){let V=Object.keys(F),S=V.length;for(let E=0;E<S;E++)Y==="strict"?O[V[E]]=[F[V[E]]]:O[V[E]]=F[V[E]]}},b.getValue=function(O){return b.isExist(O)?O:""},b.isName=G,b.getAllMatches=$,b.nameRegexp=A}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(b,P){"use strict";var N=class{static{s(this,"XmlNode")}static{r(this,"XmlNode")}constructor(A){this.tagname=A,this.child=[],this[":@"]={}}add(A,B){A==="__proto__"&&(A="#__proto__"),this.child.push({[A]:B})}addChild(A){A.tagname==="__proto__"&&(A.tagname="#__proto__"),A[":@"]&&Object.keys(A[":@"]).length>0?this.child.push({[A.tagname]:A.child,":@":A[":@"]}):this.child.push({[A.tagname]:A.child})}};P.exports=N}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(b,P){var N=a();function A(S,E){let U={};if(S[E+3]==="O"&&S[E+4]==="C"&&S[E+5]==="T"&&S[E+6]==="Y"&&S[E+7]==="P"&&S[E+8]==="E"){E=E+9;let we=1,ce=!1,le=!1,je="";for(;E<S.length;E++)if(S[E]==="<"&&!le){if(ce&&G(S,E))E+=7,[entityName,val,E]=B(S,E+1),val.indexOf("&")===-1&&(U[V(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(ce&&O(S,E))E+=8;else if(ce&&F(S,E))E+=8;else if(ce&&Y(S,E))E+=9;else if($)le=!0;else throw new Error("Invalid DOCTYPE");we++,je=""}else if(S[E]===">"){if(le?S[E-1]==="-"&&S[E-2]==="-"&&(le=!1,we--):we--,we===0)break}else S[E]==="["?ce=!0:je+=S[E];if(we!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:U,i:E}}s(A,"readDocType"),r(A,"readDocType");function B(S,E){let U="";for(;E<S.length&&S[E]!=="'"&&S[E]!=='"';E++)U+=S[E];if(U=U.trim(),U.indexOf(" ")!==-1)throw new Error("External entites are not supported");let we=S[E++],ce="";for(;E<S.length&&S[E]!==we;E++)ce+=S[E];return[U,ce,E]}s(B,"readEntityExp"),r(B,"readEntityExp");function $(S,E){return S[E+1]==="!"&&S[E+2]==="-"&&S[E+3]==="-"}s($,"isComment"),r($,"isComment");function G(S,E){return S[E+1]==="!"&&S[E+2]==="E"&&S[E+3]==="N"&&S[E+4]==="T"&&S[E+5]==="I"&&S[E+6]==="T"&&S[E+7]==="Y"}s(G,"isEntity"),r(G,"isEntity");function O(S,E){return S[E+1]==="!"&&S[E+2]==="E"&&S[E+3]==="L"&&S[E+4]==="E"&&S[E+5]==="M"&&S[E+6]==="E"&&S[E+7]==="N"&&S[E+8]==="T"}s(O,"isElement"),r(O,"isElement");function F(S,E){return S[E+1]==="!"&&S[E+2]==="A"&&S[E+3]==="T"&&S[E+4]==="T"&&S[E+5]==="L"&&S[E+6]==="I"&&S[E+7]==="S"&&S[E+8]==="T"}s(F,"isAttlist"),r(F,"isAttlist");function Y(S,E){return S[E+1]==="!"&&S[E+2]==="N"&&S[E+3]==="O"&&S[E+4]==="T"&&S[E+5]==="A"&&S[E+6]==="T"&&S[E+7]==="I"&&S[E+8]==="O"&&S[E+9]==="N"}s(Y,"isNotation"),r(Y,"isNotation");function V(S){if(N.isName(S))return S;throw new Error(`Invalid entity name ${S}`)}s(V,"validateEntityName"),r(V,"validateEntityName"),P.exports=A}}),l=o({"../../node_modules/strnum/strnum.js"(b,P){var N=/^[-+]?0x[a-fA-F0-9]+$/,A=/^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;!Number.parseInt&&window.parseInt&&(Number.parseInt=window.parseInt),!Number.parseFloat&&window.parseFloat&&(Number.parseFloat=window.parseFloat);var B={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function $(O,F={}){if(F=Object.assign({},B,F),!O||typeof O!="string")return O;let Y=O.trim();if(F.skipLike!==void 0&&F.skipLike.test(Y))return O;if(F.hex&&N.test(Y))return Number.parseInt(Y,16);{let V=A.exec(Y);if(V){let S=V[1],E=V[2],U=G(V[3]),we=V[4]||V[6];if(!F.leadingZeros&&E.length>0&&S&&Y[2]!==".")return O;if(!F.leadingZeros&&E.length>0&&!S&&Y[1]!==".")return O;{let ce=Number(Y),le=""+ce;return le.search(/[eE]/)!==-1||we?F.eNotation?ce:O:Y.indexOf(".")!==-1?le==="0"&&U===""||le===U||S&&le==="-"+U?ce:O:E?U===le||S+U===le?ce:O:Y===le||Y===S+le?ce:O}}else return O}}s($,"toNumber"),r($,"toNumber");function G(O){return O&&O.indexOf(".")!==-1&&(O=O.replace(/0+$/,""),O==="."?O="0":O[0]==="."?O="0"+O:O[O.length-1]==="."&&(O=O.substr(0,O.length-1))),O}s(G,"trimZeros"),r(G,"trimZeros"),P.exports=$}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(b,P){"use strict";var N=a(),A=c(),B=u(),$=l(),G=class{static{s(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(I){this.options=I,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"\xA2"},pound:{regex:/&(pound|#163);/g,val:"\xA3"},yen:{regex:/&(yen|#165);/g,val:"\xA5"},euro:{regex:/&(euro|#8364);/g,val:"\u20AC"},copyright:{regex:/&(copy|#169);/g,val:"\xA9"},reg:{regex:/&(reg|#174);/g,val:"\xAE"},inr:{regex:/&(inr|#8377);/g,val:"\u20B9"},num_dec:{regex:/&#([0-9]{1,7});/g,val:s((C,M)=>String.fromCharCode(Number.parseInt(M,10)),"val")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:s((C,M)=>String.fromCharCode(Number.parseInt(M,16)),"val")}},this.addExternalEntities=O,this.parseXml=E,this.parseTextData=F,this.resolveNameSpace=Y,this.buildAttributesMap=S,this.isItStopNode=le,this.replaceEntitiesValue=we,this.readStopNodeData=Q,this.saveTextToParentTag=ce,this.addChild=U}};function O(I){let C=Object.keys(I);for(let M=0;M<C.length;M++){let K=C[M];this.lastEntities[K]={regex:new RegExp("&"+K+";","g"),val:I[K]}}}s(O,"addExternalEntities"),r(O,"addExternalEntities");function F(I,C,M,K,D,q,de){if(I!==void 0&&(this.options.trimValues&&!K&&(I=I.trim()),I.length>0)){de||(I=this.replaceEntitiesValue(I));let W=this.options.tagValueProcessor(C,I,M,D,q);return W==null?I:typeof W!=typeof I||W!==I?W:this.options.trimValues?Pe(I,this.options.parseTagValue,this.options.numberParseOptions):I.trim()===I?Pe(I,this.options.parseTagValue,this.options.numberParseOptions):I}}s(F,"parseTextData"),r(F,"parseTextData");function Y(I){if(this.options.removeNSPrefix){let C=I.split(":"),M=I.charAt(0)==="/"?"/":"";if(C[0]==="xmlns")return"";C.length===2&&(I=M+C[1])}return I}s(Y,"resolveNameSpace"),r(Y,"resolveNameSpace");var V=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function S(I,C,M){if(!this.options.ignoreAttributes&&typeof I=="string"){let K=N.getAllMatches(I,V),D=K.length,q={};for(let de=0;de<D;de++){let W=this.resolveNameSpace(K[de][1]),H=K[de][4],ve=this.options.attributeNamePrefix+W;if(W.length)if(this.options.transformAttributeName&&(ve=this.options.transformAttributeName(ve)),ve==="__proto__"&&(ve="#__proto__"),H!==void 0){this.options.trimValues&&(H=H.trim()),H=this.replaceEntitiesValue(H);let he=this.options.attributeValueProcessor(W,H,C);he==null?q[ve]=H:typeof he!=typeof H||he!==H?q[ve]=he:q[ve]=Pe(H,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(q[ve]=!0)}if(!Object.keys(q).length)return;if(this.options.attributesGroupName){let de={};return de[this.options.attributesGroupName]=q,de}return q}}s(S,"buildAttributesMap"),r(S,"buildAttributesMap");var E=r(function(I){I=I.replace(/\r\n?/g,`
|
|
94
|
+
`);let C=new A("!xml"),M=C,K="",D="";for(let q=0;q<I.length;q++)if(I[q]==="<")if(I[q+1]==="/"){let W=R(I,">",q,"Closing Tag is not closed."),H=I.substring(q+2,W).trim();if(this.options.removeNSPrefix){let We=H.indexOf(":");We!==-1&&(H=H.substr(We+1))}this.options.transformTagName&&(H=this.options.transformTagName(H)),M&&(K=this.saveTextToParentTag(K,M,D));let ve=D.substring(D.lastIndexOf(".")+1);if(H&&this.options.unpairedTags.indexOf(H)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${H}>`);let he=0;ve&&this.options.unpairedTags.indexOf(ve)!==-1?(he=D.lastIndexOf(".",D.lastIndexOf(".")-1),this.tagsNodeStack.pop()):he=D.lastIndexOf("."),D=D.substring(0,he),M=this.tagsNodeStack.pop(),K="",q=W}else if(I[q+1]==="?"){let W=_(I,q,!1,"?>");if(!W)throw new Error("Pi Tag is not closed.");if(K=this.saveTextToParentTag(K,M,D),!(this.options.ignoreDeclaration&&W.tagName==="?xml"||this.options.ignorePiTags)){let H=new A(W.tagName);H.add(this.options.textNodeName,""),W.tagName!==W.tagExp&&W.attrExpPresent&&(H[":@"]=this.buildAttributesMap(W.tagExp,D,W.tagName)),this.addChild(M,H,D)}q=W.closeIndex+1}else if(I.substr(q+1,3)==="!--"){let W=R(I,"-->",q+4,"Comment is not closed.");if(this.options.commentPropName){let H=I.substring(q+4,W-2);K=this.saveTextToParentTag(K,M,D),M.add(this.options.commentPropName,[{[this.options.textNodeName]:H}])}q=W}else if(I.substr(q+1,2)==="!D"){let W=B(I,q);this.docTypeEntities=W.entities,q=W.i}else if(I.substr(q+1,2)==="!["){let W=R(I,"]]>",q,"CDATA is not closed.")-2,H=I.substring(q+9,W);K=this.saveTextToParentTag(K,M,D);let ve=this.parseTextData(H,M.tagname,D,!0,!1,!0,!0);ve==null&&(ve=""),this.options.cdataPropName?M.add(this.options.cdataPropName,[{[this.options.textNodeName]:H}]):M.add(this.options.textNodeName,ve),q=W+2}else{let W=_(I,q,this.options.removeNSPrefix),H=W.tagName,ve=W.rawTagName,he=W.tagExp,We=W.attrExpPresent,_a=W.closeIndex;this.options.transformTagName&&(H=this.options.transformTagName(H)),M&&K&&M.tagname!=="!xml"&&(K=this.saveTextToParentTag(K,M,D,!1));let ka=M;if(ka&&this.options.unpairedTags.indexOf(ka.tagname)!==-1&&(M=this.tagsNodeStack.pop(),D=D.substring(0,D.lastIndexOf("."))),H!==C.tagname&&(D+=D?"."+H:H),this.isItStopNode(this.options.stopNodes,D,H)){let ze="";if(he.length>0&&he.lastIndexOf("/")===he.length-1)q=W.closeIndex;else if(this.options.unpairedTags.indexOf(H)!==-1)q=W.closeIndex;else{let Oo=this.readStopNodeData(I,ve,_a+1);if(!Oo)throw new Error(`Unexpected end of ${ve}`);q=Oo.i,ze=Oo.tagContent}let Co=new A(H);H!==he&&We&&(Co[":@"]=this.buildAttributesMap(he,D,H)),ze&&(ze=this.parseTextData(ze,H,D,!0,We,!0,!0)),D=D.substr(0,D.lastIndexOf(".")),Co.add(this.options.textNodeName,ze),this.addChild(M,Co,D)}else{if(he.length>0&&he.lastIndexOf("/")===he.length-1){H[H.length-1]==="/"?(H=H.substr(0,H.length-1),D=D.substr(0,D.length-1),he=H):he=he.substr(0,he.length-1),this.options.transformTagName&&(H=this.options.transformTagName(H));let ze=new A(H);H!==he&&We&&(ze[":@"]=this.buildAttributesMap(he,D,H)),this.addChild(M,ze,D),D=D.substr(0,D.lastIndexOf("."))}else{let ze=new A(H);this.tagsNodeStack.push(M),H!==he&&We&&(ze[":@"]=this.buildAttributesMap(he,D,H)),this.addChild(M,ze,D),M=ze}K="",q=_a}}else K+=I[q];return C.child},"parseXml");function U(I,C,M){let K=this.options.updateTag(C.tagname,M,C[":@"]);K===!1||(typeof K=="string"&&(C.tagname=K),I.addChild(C))}s(U,"addChild"),r(U,"addChild");var we=r(function(I){if(this.options.processEntities){for(let C in this.docTypeEntities){let M=this.docTypeEntities[C];I=I.replace(M.regx,M.val)}for(let C in this.lastEntities){let M=this.lastEntities[C];I=I.replace(M.regex,M.val)}if(this.options.htmlEntities)for(let C in this.htmlEntities){let M=this.htmlEntities[C];I=I.replace(M.regex,M.val)}I=I.replace(this.ampEntity.regex,this.ampEntity.val)}return I},"replaceEntitiesValue");function ce(I,C,M,K){return I&&(K===void 0&&(K=Object.keys(C.child).length===0),I=this.parseTextData(I,C.tagname,M,!1,C[":@"]?Object.keys(C[":@"]).length!==0:!1,K),I!==void 0&&I!==""&&C.add(this.options.textNodeName,I),I=""),I}s(ce,"saveTextToParentTag"),r(ce,"saveTextToParentTag");function le(I,C,M){let K="*."+M;for(let D in I){let q=I[D];if(K===q||C===q)return!0}return!1}s(le,"isItStopNode"),r(le,"isItStopNode");function je(I,C,M=">"){let K,D="";for(let q=C;q<I.length;q++){let de=I[q];if(K)de===K&&(K="");else if(de==='"'||de==="'")K=de;else if(de===M[0])if(M[1]){if(I[q+1]===M[1])return{data:D,index:q}}else return{data:D,index:q};else de===" "&&(de=" ");D+=de}}s(je,"tagExpWithClosingIndex"),r(je,"tagExpWithClosingIndex");function R(I,C,M,K){let D=I.indexOf(C,M);if(D===-1)throw new Error(K);return D+C.length-1}s(R,"findClosingIndex"),r(R,"findClosingIndex");function _(I,C,M,K=">"){let D=je(I,C+1,K);if(!D)return;let q=D.data,de=D.index,W=q.search(/\s/),H=q,ve=!0;W!==-1&&(H=q.substring(0,W),q=q.substring(W+1).trimStart());let he=H;if(M){let We=H.indexOf(":");We!==-1&&(H=H.substr(We+1),ve=H!==D.data.substr(We+1))}return{tagName:H,tagExp:q,closeIndex:de,attrExpPresent:ve,rawTagName:he}}s(_,"readTagExp"),r(_,"readTagExp");function Q(I,C,M){let K=M,D=1;for(;M<I.length;M++)if(I[M]==="<")if(I[M+1]==="/"){let q=R(I,">",M,`${C} is not closed`);if(I.substring(M+2,q).trim()===C&&(D--,D===0))return{tagContent:I.substring(K,M),i:q};M=q}else if(I[M+1]==="?")M=R(I,"?>",M+1,"StopNode is not closed.");else if(I.substr(M+1,3)==="!--")M=R(I,"-->",M+3,"StopNode is not closed.");else if(I.substr(M+1,2)==="![")M=R(I,"]]>",M,"StopNode is not closed.")-2;else{let q=_(I,M,">");q&&((q&&q.tagName)===C&&q.tagExp[q.tagExp.length-1]!=="/"&&D++,M=q.closeIndex)}}s(Q,"readStopNodeData"),r(Q,"readStopNodeData");function Pe(I,C,M){if(C&&typeof I=="string"){let K=I.trim();return K==="true"?!0:K==="false"?!1:$(I,M)}else return N.isExist(I)?I:""}s(Pe,"parseValue"),r(Pe,"parseValue"),P.exports=G}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(b){"use strict";function P(G,O){return N(G,O)}s(P,"prettify"),r(P,"prettify");function N(G,O,F){let Y,V={};for(let S=0;S<G.length;S++){let E=G[S],U=A(E),we="";if(F===void 0?we=U:we=F+"."+U,U===O.textNodeName)Y===void 0?Y=E[U]:Y+=""+E[U];else{if(U===void 0)continue;if(E[U]){let ce=N(E[U],O,we),le=$(ce,O);E[":@"]?B(ce,E[":@"],we,O):Object.keys(ce).length===1&&ce[O.textNodeName]!==void 0&&!O.alwaysCreateTextNode?ce=ce[O.textNodeName]:Object.keys(ce).length===0&&(O.alwaysCreateTextNode?ce[O.textNodeName]="":ce=""),V[U]!==void 0&&V.hasOwnProperty(U)?(Array.isArray(V[U])||(V[U]=[V[U]]),V[U].push(ce)):O.isArray(U,we,le)?V[U]=[ce]:V[U]=ce}}}return typeof Y=="string"?Y.length>0&&(V[O.textNodeName]=Y):Y!==void 0&&(V[O.textNodeName]=Y),V}s(N,"compress"),r(N,"compress");function A(G){let O=Object.keys(G);for(let F=0;F<O.length;F++){let Y=O[F];if(Y!==":@")return Y}}s(A,"propName"),r(A,"propName");function B(G,O,F,Y){if(O){let V=Object.keys(O),S=V.length;for(let E=0;E<S;E++){let U=V[E];Y.isArray(U,F+"."+U,!0,!0)?G[U]=[O[U]]:G[U]=O[U]}}}s(B,"assignAttributes"),r(B,"assignAttributes");function $(G,O){let{textNodeName:F}=O,Y=Object.keys(G).length;return!!(Y===0||Y===1&&(G[F]||typeof G[F]=="boolean"||G[F]===0))}s($,"isLeafTag"),r($,"isLeafTag"),b.prettify=P}}),m=o({"node_modules/fast-xml-parser/src/validator.js"(b){"use strict";var P=a(),N={allowBooleanAttributes:!1,unpairedTags:[]};b.validate=function(R,_){_=Object.assign({},N,_);let Q=[],Pe=!1,I=!1;R[0]==="\uFEFF"&&(R=R.substr(1));for(let C=0;C<R.length;C++)if(R[C]==="<"&&R[C+1]==="?"){if(C+=2,C=B(R,C),C.err)return C}else if(R[C]==="<"){let M=C;if(C++,R[C]==="!"){C=$(R,C);continue}else{let K=!1;R[C]==="/"&&(K=!0,C++);let D="";for(;C<R.length&&R[C]!==">"&&R[C]!==" "&&R[C]!==" "&&R[C]!==`
|
|
95
|
+
`&&R[C]!=="\r";C++)D+=R[C];if(D=D.trim(),D[D.length-1]==="/"&&(D=D.substring(0,D.length-1),C--),!ce(D)){let W;return D.trim().length===0?W="Invalid space after '<'.":W="Tag '"+D+"' is an invalid name.",U("InvalidTag",W,le(R,C))}let q=F(R,C);if(q===!1)return U("InvalidAttr","Attributes for '"+D+"' have open quote.",le(R,C));let de=q.value;if(C=q.index,de[de.length-1]==="/"){let W=C-de.length;de=de.substring(0,de.length-1);let H=V(de,_);if(H===!0)Pe=!0;else return U(H.err.code,H.err.msg,le(R,W+H.err.line))}else if(K)if(q.tagClosed){if(de.trim().length>0)return U("InvalidTag","Closing tag '"+D+"' can't have attributes or invalid starting.",le(R,M));{let W=Q.pop();if(D!==W.tagName){let H=le(R,W.tagStartPos);return U("InvalidTag","Expected closing tag '"+W.tagName+"' (opened in line "+H.line+", col "+H.col+") instead of closing tag '"+D+"'.",le(R,M))}Q.length==0&&(I=!0)}}else return U("InvalidTag","Closing tag '"+D+"' doesn't have proper closing.",le(R,C));else{let W=V(de,_);if(W!==!0)return U(W.err.code,W.err.msg,le(R,C-de.length+W.err.line));if(I===!0)return U("InvalidXml","Multiple possible root nodes found.",le(R,C));_.unpairedTags.indexOf(D)!==-1||Q.push({tagName:D,tagStartPos:M}),Pe=!0}for(C++;C<R.length;C++)if(R[C]==="<")if(R[C+1]==="!"){C++,C=$(R,C);continue}else if(R[C+1]==="?"){if(C=B(R,++C),C.err)return C}else break;else if(R[C]==="&"){let W=E(R,C);if(W==-1)return U("InvalidChar","char '&' is not expected.",le(R,C));C=W}else if(I===!0&&!A(R[C]))return U("InvalidXml","Extra text at the end",le(R,C));R[C]==="<"&&C--}}else{if(A(R[C]))continue;return U("InvalidChar","char '"+R[C]+"' is not expected.",le(R,C))}if(Pe){if(Q.length==1)return U("InvalidTag","Unclosed tag '"+Q[0].tagName+"'.",le(R,Q[0].tagStartPos));if(Q.length>0)return U("InvalidXml","Invalid '"+JSON.stringify(Q.map(C=>C.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return U("InvalidXml","Start tag expected.",1);return!0};function A(R){return R===" "||R===" "||R===`
|
|
96
|
+
`||R==="\r"}s(A,"isWhiteSpace"),r(A,"isWhiteSpace");function B(R,_){let Q=_;for(;_<R.length;_++)if(R[_]=="?"||R[_]==" "){let Pe=R.substr(Q,_-Q);if(_>5&&Pe==="xml")return U("InvalidXml","XML declaration allowed only at the start of the document.",le(R,_));if(R[_]=="?"&&R[_+1]==">"){_++;break}else continue}return _}s(B,"readPI"),r(B,"readPI");function $(R,_){if(R.length>_+5&&R[_+1]==="-"&&R[_+2]==="-"){for(_+=3;_<R.length;_++)if(R[_]==="-"&&R[_+1]==="-"&&R[_+2]===">"){_+=2;break}}else if(R.length>_+8&&R[_+1]==="D"&&R[_+2]==="O"&&R[_+3]==="C"&&R[_+4]==="T"&&R[_+5]==="Y"&&R[_+6]==="P"&&R[_+7]==="E"){let Q=1;for(_+=8;_<R.length;_++)if(R[_]==="<")Q++;else if(R[_]===">"&&(Q--,Q===0))break}else if(R.length>_+9&&R[_+1]==="["&&R[_+2]==="C"&&R[_+3]==="D"&&R[_+4]==="A"&&R[_+5]==="T"&&R[_+6]==="A"&&R[_+7]==="["){for(_+=8;_<R.length;_++)if(R[_]==="]"&&R[_+1]==="]"&&R[_+2]===">"){_+=2;break}}return _}s($,"readCommentAndCDATA"),r($,"readCommentAndCDATA");var G='"',O="'";function F(R,_){let Q="",Pe="",I=!1;for(;_<R.length;_++){if(R[_]===G||R[_]===O)Pe===""?Pe=R[_]:Pe!==R[_]||(Pe="");else if(R[_]===">"&&Pe===""){I=!0;break}Q+=R[_]}return Pe!==""?!1:{value:Q,index:_,tagClosed:I}}s(F,"readAttributeStr"),r(F,"readAttributeStr");var Y=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function V(R,_){let Q=P.getAllMatches(R,Y),Pe={};for(let I=0;I<Q.length;I++){if(Q[I][1].length===0)return U("InvalidAttr","Attribute '"+Q[I][2]+"' has no space in starting.",je(Q[I]));if(Q[I][3]!==void 0&&Q[I][4]===void 0)return U("InvalidAttr","Attribute '"+Q[I][2]+"' is without value.",je(Q[I]));if(Q[I][3]===void 0&&!_.allowBooleanAttributes)return U("InvalidAttr","boolean attribute '"+Q[I][2]+"' is not allowed.",je(Q[I]));let C=Q[I][2];if(!we(C))return U("InvalidAttr","Attribute '"+C+"' is an invalid name.",je(Q[I]));if(!Pe.hasOwnProperty(C))Pe[C]=1;else return U("InvalidAttr","Attribute '"+C+"' is repeated.",je(Q[I]))}return!0}s(V,"validateAttributeString"),r(V,"validateAttributeString");function S(R,_){let Q=/\d/;for(R[_]==="x"&&(_++,Q=/[\da-fA-F]/);_<R.length;_++){if(R[_]===";")return _;if(!R[_].match(Q))break}return-1}s(S,"validateNumberAmpersand"),r(S,"validateNumberAmpersand");function E(R,_){if(_++,R[_]===";")return-1;if(R[_]==="#")return _++,S(R,_);let Q=0;for(;_<R.length;_++,Q++)if(!(R[_].match(/\w/)&&Q<20)){if(R[_]===";")break;return-1}return _}s(E,"validateAmpersand"),r(E,"validateAmpersand");function U(R,_,Q){return{err:{code:R,msg:_,line:Q.line||Q,col:Q.col}}}s(U,"getErrorObject"),r(U,"getErrorObject");function we(R){return P.isName(R)}s(we,"validateAttrName"),r(we,"validateAttrName");function ce(R){return P.isName(R)}s(ce,"validateTagName"),r(ce,"validateTagName");function le(R,_){let Q=R.substring(0,_).split(/\r?\n/);return{line:Q.length,col:Q[Q.length-1].length+1}}s(le,"getLineNumberForPosition"),r(le,"getLineNumberForPosition");function je(R){return R.startIndex+R[1].length}s(je,"getPositionFromMatch"),r(je,"getPositionFromMatch")}}),h=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(b,P){var{buildOptions:N}=i(),A=d(),{prettify:B}=p(),$=m(),G=class{static{s(this,"XMLParser")}static{r(this,"XMLParser")}constructor(O){this.externalEntities={},this.options=N(O)}parse(O,F){if(typeof O!="string")if(O.toString)O=O.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(F){F===!0&&(F={});let S=$.validate(O,F);if(S!==!0)throw Error(`${S.err.msg}:${S.err.line}:${S.err.col}`)}let Y=new A(this.options);Y.addExternalEntities(this.externalEntities);let V=Y.parseXml(O);return this.options.preserveOrder||V===void 0?V:B(V,this.options)}addEntity(O,F){if(F.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(O.indexOf("&")!==-1||O.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '
'");if(F==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[O]=F}};P.exports=G}});let w=h();return new w(n)},"getXmlParser");var Sa=class extends Pt{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),g("policy.outbound.xml-to-json"),te(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?vt(e.parseOnStatusCodes):void 0,this.parser=Bl({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let c=await e.text();o=this.parser.parse(c)}catch(c){let u=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(u,c),new k(u)}let i=new Headers(e.headers);return i.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:i})}};var Ca=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new ae(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var Gl=10,Vl=3e4,yr=class{static{s(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,t){if(typeof t=="number"){let r=t;this.#n=r*1e3,this.#o=Vl,this.#r=Gl}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:Vl,this.#r=Gl}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#c(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#c(e);if(t)return this.#u(e),t;if(this.#a(e))try{await vh(()=>this.#c(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#c(e);if(r)return r}catch{}return this.#l(e)}#u(e){if(!this.#a(e)){let t=this.#l(e);It().waitUntil(t)}}async#l(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new f(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function vh(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new f(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}s(vh,"waitUntilTrue");var Oa=["sha-1","sha-256","sha-384","sha-512"],So=class{static{s(this,"BaseCryptoBeta")}};var Aa=class extends So{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(g("runtime.crypto-beta"),!Oa.includes(e.toLowerCase()))throw new k(`Algorithm ${e} is not supported. Try using ${Oa.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(c=>c.toString(16).padStart(2,"0")).join("")}};export{fs as AWSLoggingPlugin,Ls as AkamaiApiSecurityPlugin,zf as AmberfloMeteringInboundPolicy,Gs as AmberfloMeteringPolicy,Vf as ApiAuthKeyInboundPolicy,Vs as ApiKeyInboundPolicy,Ws as AsertoAuthZInboundPolicy,Ss as AuditLogDataStaxProvider,Cs as AuditLogPlugin,Yf as Auth0JwtInboundPolicy,Ys as AuthZenInboundPolicy,Sp as AwsLambdaHandlerExtensions,Xs as AxiomaticsAuthZInboundPolicy,Ds as AzureBlobPlugin,Zs as AzureEventHubsRequestLoggerPlugin,br as BackgroundDispatcher,yr as BackgroundLoader,eg as BasicAuthInboundPolicy,Al as BasicRateLimitInboundPolicy,ie as BatchDispatch,na as BrownoutInboundPolicy,dg as CachingInboundPolicy,pg as ChangeMethodInboundPolicy,mg as ClearHeadersInboundPolicy,fg as ClearHeadersOutboundPolicy,gg as ClerkJwtInboundPolicy,hg as CognitoJwtInboundPolicy,ca as ComplexRateLimitInboundPolicy,Eg as CompositeInboundPolicy,Tg as CompositeOutboundPolicy,f as ConfigurationError,ci as ContentTypes,fe as ContextData,Aa as CryptoBeta,Sg as CurityPhantomTokenInboundPolicy,Mi as DataDogLoggingPlugin,ws as DataDogMetricsPlugin,rs as DynaTraceLoggingPlugin,xs as DynatraceMetricsPlugin,Og as FirebaseJwtInboundPolicy,Ag as FormDataToJsonInboundPolicy,_g as GeoFilterInboundPolicy,Ai as GoogleCloudLoggingPlugin,$i as Handler,T as HttpProblems,Ur as HttpStatusCode,qs as HydrolixRequestLoggerPlugin,ye as InboundPolicy,kg as JWTScopeValidationInboundPolicy,as as LokiLoggingPlugin,pn as LookupResult,me as MemoryZoneReadThroughCache,Lg as MockApiInboundPolicy,Ug as MoesifInboundPolicy,pa as MonetizationInboundPolicy,is as NewRelicLoggingPlugin,Es as NewRelicMetricsPlugin,ma as OktaFGAAuthZInboundPolicy,Fg as OktaJwtInboundPolicy,fa as OpenFGAAuthZInboundPolicy,Me as OpenIdJwtInboundPolicy,Pt as OutboundPolicy,Dt as ProblemResponseFormatter,zg as PropelAuthJwtInboundPolicy,ya as QuotaInboundPolicy,Al as RateLimitInboundPolicy,Kg as ReadmeMetricsInboundPolicy,Qg as RemoveHeadersInboundPolicy,Yg as RemoveHeadersOutboundPolicy,Xg as RemoveQueryParamsInboundPolicy,eh as ReplaceStringOutboundPolicy,$s as RequestLoggerPlugin,th as RequestSizeLimitInboundPolicy,ql as RequestValidationInboundPolicy,rh as RequireOriginInboundPolicy,Jn as ResponseSendingEvent,Kn as ResponseSentEvent,k as RuntimeError,Lr as SYSTEM_LOGGER,nh as SchemaBasedRequestValidation,lt as SemanticAttributes,Ca as ServiceProviderImpl,oh as SetBodyInboundPolicy,ih as SetHeadersInboundPolicy,sh as SetHeadersOutboundPolicy,ah as SetQueryParamsInboundPolicy,ch as SetStatusOutboundPolicy,lh as SleepInboundPolicy,hs as SplunkLoggingPlugin,Go as StreamingZoneCache,el as StripeMonetizationPlugin,wr as StripeWebhookVerificationInboundPolicy,ls as SumoLogicLoggingPlugin,dh as SupabaseJwtInboundPolicy,bt as SystemRouteName,Vn as TelemetryPlugin,ph as UpstreamAzureAdServiceAuthInboundPolicy,fh as UpstreamFirebaseAdminAuthInboundPolicy,yh as UpstreamFirebaseUserAuthInboundPolicy,Pa as UpstreamGcpFederatedAuthInboundPolicy,bh as UpstreamGcpJwtInboundPolicy,wh as UpstreamGcpServiceAuthInboundPolicy,ps as VMWareLogInsightLoggingPlugin,Rh as ValidateJsonSchemaInbound,Sa as XmlToJsonOutboundPolicy,$n as ZoneCache,ue as ZuploRequest,xr as ZuploServices,Rd as apiServices,Cp as awsLambdaHandler,_f as defaultGenerateHydrolixEntry,Se as environment,Ao as getIdForParameterSchema,Ql as getIdForRefSchema,_o as getIdForRequestBodySchema,Kl as getRawOperationDataIdentifierName,di as httpStatuses,uf as mcpServerHandler,Dp as openApiSpecHandler,qp as redirectHandler,Yl as sanitizedIdentifierName,ui as serialize,Zg as setMoesifContext,g as trackFeature,Hp as urlForwardHandler,jp as urlRewriteHandler,zp as webSocketHandler,Bp as webSocketPipelineHandler,$p as zuploServiceProxy};
|
|
97
97
|
/*! For license information please see index.js.LEGAL.txt */
|