@zuplo/runtime 5.2289.0 → 5.2290.0

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 CHANGED
@@ -22,7 +22,7 @@
22
22
  * DEALINGS IN THE SOFTWARE.
23
23
  *--------------------------------------------------------------------------------------------*/
24
24
 
25
- import{a as Ue,d as be,e as ua,f as _n,g as Nn,h as ca,i as la}from"./chunk-FYAUORKR.js";import{a as Ve,b as K,c as M,d as m,e as Wo,f as $,g as Ko}from"./chunk-ZRDXIUWC.js";import{a as y}from"./chunk-KKIQMPVP.js";import{a as s,c as ze}from"./chunk-4DUPDUSC.js";Function.prototype.toString=function(){return"[native code]"};var $t=globalThis,Jo=$t.caches;if(Jo){let n=Jo.open;$t.caches.open=function(e){let t=y.instance.deploymentName??y.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete $t.caches.default,Object.freeze($t.caches)}var Yo=new Map,Dn=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)})}},nt=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Yo.get(e);r||(r=new Dn(t),Yo.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 Mn="__zuplo-expiry-header",Pt=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(Mn);if(!i){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),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(Mn,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await i.put(a,u)}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(Mn,`${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 ue=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new nt(r),this.#n=new Pt(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)}};var Xo="zuplo-request-id",Ge="zp-rid",Hn="zp-body-removed",We="cf-ray",Qo="x-real-ip",Un="cf-ipcity",Zn="cf-ipcontinent",qn="cf-ipcountry",Fn="cf-iplongitude",$n="cf-iplatitude",ei="cf-region",ti="cf-region-code",ni="cf-metro-code",ri="cf-postal-code",oi="cf-timezone",ii="zp-ipcity",si="zp-ipcontinent",ai="zp-ipcountry",ui="zp-iplongitude",ci="zp-iplatitude",li="true-client-ip",jn="zp-asn",Bn="zp-asorg",zn="zp-colo",Vn="zp-postalcode",Gn="zp-metrocode",Wn="zp-region",Kn="zp-regioncode",Jn="zp-timezone",di=[Un,Zn,qn,Fn,$n,jn,Bn,zn,Vn,Gn,Wn,Kn,Jn],pi=["zp-","cf-"],mi=[Ge,We,Hn];var It=Symbol("zuplo_meters"),jt=Symbol("zuplo_dynamic_meters"),Bt="system-logger";var Qi=ze(Ve());import{trace as Wa}from"@opentelemetry/api";import{SpanStatusCode as da,trace as pa}from"@opentelemetry/api";import{SpanStatusCode as er,trace as tr}from"@opentelemetry/api";var gi=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function fi(n){gi=n}s(fi,"setTelemetryInitFunction");var hi=s(n=>gi(n),"proxyHandler");var Ze=class{static{s(this,"RuntimePlugin")}},De=class extends Ze{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},zt=class extends De{static{s(this,"MeteringPlugin")}},Et=class extends Ze{static{s(this,"TelemetryPlugin")}};var Vt=new Set,yi=new Set;function h(n){yi.has(n)||(yi.add(n),Vt.add(n))}s(h,"trackFeature");function bi(){let n=[...Vt];return Vt.clear(),n}s(bi,"getUnsentFeatures");function wi(n){for(let e of n)Vt.add(e)}s(wi,"restoreFeatures");var xt=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=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"}})};static setProblemResponseFormat(e){e&&(h("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new M("Error in custom 'problemResponseFormat'",{cause:i})}})}},Ke=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await xt.problemResponseFormat(e,t,r)}};function Gt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Gt(t)}return Object.freeze(n)}s(Gt,"deepFreeze");var ee=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 Gt(this.#e)}get params(){return Gt(this.#t)}user};var Tt={},Me=[],Yn=[],Xn=[],Qn=[];var Wt={addPlugin(n){Me.push(n)},addRequestHook(n){Yn.push(n)},addResponseSendingHook(n){Xn.push(n)},addResponseSendingFinalHook(n){Qn.push(n)}},Pi=s(async(n,e)=>{if(Yn.length===0)return n;let t=tr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of Yn){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(o,e);if(c instanceof ee||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:er.ERROR}),l}});if(a instanceof ee)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Ii=s(async(n,e,t)=>{if(Xn.length===0)return n;let r=tr.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of Xn)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)i=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw u.recordException(l),u.setStatus({code:er.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Ei=s(async(n,e,t)=>{if(Qn.length===0)return;let r=tr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of Qn)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:er.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Ri=!1;async function xi(n){if(!Ri){n&&(h("runtime.extensions"),await n(Wt)),Tt.value=Wt;for(let e of Me)if(e instanceof Et){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});fi(t)}for(let e of Me)e instanceof De&&await e.initialize(Wt);xt.setProblemResponseFormat(Wt.problemResponseFormat),Ri=!0}}s(xi,"initializeRuntime");var nr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function rr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(nr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(nr.Json)||!e?JSON.stringify(n):n}s(rr,"serialize");function rt(n){return me.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(me.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(rt,"isSystemRoute");var ce=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>pa.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:da.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async P=>{let S=a.pop();return S?S(o,i,t,u):await this.#e(async j=>{let Z=await r(j,i);return ma(Z)},t)(P,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(rt(d)&&y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new vt(o,l);i.dispatchEvent(p);let g=ge.getContextExtensions(i),f=g.latestRequest,O;try{O=await p.mutableResponse}catch(P){return i.log.error(P),t.errorHandler(o,i,P)}try{O=await g.onResponseSending(O,f,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,i,P)}try{O=await Ii(O,f,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,i,P)}i.dispatchEvent(new St(o,O));try{await g.onResponseSendingFinal(l,f,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Ei(l,f,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return O}};function ma(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(rr(n),{headers:{"content-type":"application/json"}})}s(ma,"resultToResponse");var Kt=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(Kt||{}),Ti={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 ga={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"},or=ga;function fa(n){return`${new URL(n.url).pathname}`}s(fa,"instance");function ha(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=n.headers.get(We);return r&&(t.rayId=r),t}s(ha,"trace");var ya=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:fa(e),trace:ha(e,t),...r},additionalHeaders:o,statusText:or[n.status]}),"merge"),ir=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Ke.format(e,t,r):Ke.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Ti[e],...t}}},T=class extends ir{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=ya(this.getProblemFromStatus(e),t,r,o,i);return Ke.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var qe=class extends Ze{static{s(this,"MetricsPlugin")}};var Y=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 K(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var J=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=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)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Jt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=y.instance.loggingId,this.#e=e,this.#t=new J("ellie-metrics-transport",10,this.dispatchFunction,Y.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=y.instance,{ACCOUNT_NAME:o,PROJECT_NAME:i}=y.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=bi(),c={metadata:{timestamp:new Date,accountName:o,projectName:i,deploymentName:r},metrics:a,features:u},l=await $.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":y.instance.deploymentName??"unknown","user-agent":y.instance.systemUserAgent}});if(!l.ok){let d=await l.text();Y.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),wi(u)}}};var ie=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.version=Ct.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Ct={name:"__system-no-version",pathPrefix:""};var fe=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get(We)??void 0,c=n.headers.get(li)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ie&&(d=e.route.systemRouteName);let p=ge.getContextExtensions(e).latestRequest,g={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,requestId:e.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:u,instanceId:y.instance.instanceId,userSub:p.user?.sub,clientIp:c},f=[];return f.push(new Jt(e)),Me.forEach(O=>{if(O instanceof qe){let P=O.getTransport();f.push(P)}}),f.forEach(O=>{O.pushMetrics(g,e)}),a},"metricsProcessor");var sr=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return T.notFound(i,a);let l=y.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&Y.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new ce({processors:[fe],handler:t,gateway:e}),o=new ie({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:ba}=Object.prototype,{propertyIsEnumerable:wa}=Object.prototype;function ar(n){return ba.call(n)}s(ar,"toString");function Ie(n){return typeof n=="string"}s(Ie,"isString");function ot(n){return Ie(n)&&n!==""}s(ot,"isNonEmptyString");function vi(n){return ar(n)==="[object RegExp]"}s(vi,"isRegexp");function Si(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>wa.call(n,e))]}s(Si,"getOwnEnumerableKeys");function Je(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Je,"isObject");function ur(n){return typeof n=="number"&&!isNaN(n)}s(ur,"isNumber");function cr(n){return n===!0||n===!1}s(cr,"isBoolean");function Ci(n){return typeof n>"u"}s(Ci,"isUndefined");function Oi(n){return Ci(n)||n===null}s(Oi,"isUndefinedOrNull");function Ot(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Ot,"isErrorLike");var Ai=new Map;function it(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 Error("Malformed input string");let e=Ai.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),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Ai.set(n,r),r}s(it,"statusCodesStringToNumberArray");function Ye(n,e,t){if(!e.startsWith("."))throw new m(`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 M(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ye,"getValueFromRequestUser");function Xe(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Ie(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}s(Xe,"parseValueToStringArray");function Li(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!Je(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ot(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!ur(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!cr(t.allowCredentials))throw new m("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=lr(t,"allowedHeaders"),o=lr(t,"allowedMethods"),i=lr(t,"exposeHeaders"),a;try{a=Xe(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.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(Li,"parseCorsPolicies");function lr(n,e){let t;if(n[e]!==void 0)try{t=Xe(n[e])}catch(r){throw new m(`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(lr,"parseOptionalProperty");var Yt=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"),Xt=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 dr=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=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,u,{detail:"Expect headers origin and access-control-request-method"});let g=n.lookup(l,c);if(!g)return T.notFound(a,u);let f=g.routeConfiguration,O=Ra(l,d,p,f,t);return O.isValid?new Response(void 0,{status:200,statusText:"OK",headers:O.headers}):(O.error&&u.log.warn(O.error),T.notFound(a,u))},"optionsHandler"),o=new ce({processors:[fe],handler:r,gateway:e}),i=new ie({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),Ra=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 m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=Yt(a.allowedOrigins,t);return u?{isValid:!0,headers:Xt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var ki=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 ce({processors:[fe],handler:t,gateway:e}),o=new ie({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 pr=new ie({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),_i=s((n,e)=>{let t=s(async(o,i)=>{let a=Tt.value?.notFoundHandler;if(a){let u=ge.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return T.notFound(o,i)},"notFoundHandler"),r=new ce({processors:[fe],handler:t,gateway:e});n.addRoute(pr,r.execute)},"registerNotMatchedHandler");var Pa=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ni=s(n=>{Pa.forEach(e=>n.delete(e))},"stripCorsHeaders"),Qt=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 Ni(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 K(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Ia(o,t.routeData.corsPolicies),u=Ea(n,a),c=new Headers(i.headers);return Ni(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),Ia=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 m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),Ea=s((n,e)=>{let t=Yt(e.allowedOrigins,n.headers.get("origin"));return t?Xt(e,t):{}},"getCorsHeaders");var mr=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 ce({processors:[Qt],handler:t,gateway:e}),o=new ie({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as Di,trace as Mi}from"@opentelemetry/api";var Le={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 en=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ie(t))throw new M(`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}},pe=class extends en{static{s(this,"InboundPolicy")}},Fe=class extends en{static{s(this,"OutboundPolicy")}};var hr=class extends pe{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)}},yr=class extends Fe{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)}},gr=new Map;function At(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!gr.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new m(`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 m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof pe)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new hr(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);gr.set(a.name,c)}),t.map(i=>{let a=gr.get(i);if(a===void 0)throw new M("Internal error. Policy not found in cache.");return a})}s(At,"getInboundPolicyInstances");var fr=new Map;function xa(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!fr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new m(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Fe)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new yr(a,i.handler.options??{},i.name);else throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);fr.set(i.name,u)}),t.map(o=>{let i=fr.get(o);if(i===void 0)throw new M("Internal error. Policy not found in cache.");return i})}s(xa,"getOutboundPolicyInstances");var br=s(n=>async(e,t)=>{let r=ge.getContextExtensions(t),o=Mi.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof ee||p instanceof Response)return d.end(),p;{let g=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Di.ERROR}),d.recordException(g),g}});if(l instanceof ee)u=l;else if(l instanceof Request)u=new ee(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),Ta=s(n=>async(e,t,r)=>{let o=Mi.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Le.PolicyName,c.policyName),d.setAttribute(Le.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let g=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Di.ERROR}),d.recordException(g),g}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),tn=s(async(n,e,t,r)=>{let o=At(e.route,t.routeData.policies),i=xa(e.route,t.routeData.policies);return Ui({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function Hi({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Ui({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Hi,"createInternalPolicyProcessor");async function Ui({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=br(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=Ta(r),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}s(Ui,"executePolicyProcessor");function Zi(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||va,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Sa(l,o)}i=u+1}return t}s(Zi,"parse");function va(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(va,"decode");function Sa(n,e){try{return e(n)}catch{return n}}s(Sa,"tryDecode");function qi(n,e){try{let t=/v\d+(-\d+)?/g,o=Zi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(qi,"devPortalBaseURL");var Fi="/__zuplo/dev-portal",Ca="dev-portal-id",Oa="dev-portal-host",Aa="zp-account",La="zp-project",ka="dev-portal-build",_a=`
25
+ import{a as qe,d as we,e as ya,f as Hn,g as qn,h as ba,i as wa}from"./chunk-FYAUORKR.js";import{a as Ve,b as W,c as _,d as m,e as Qo,f as F,g as ei}from"./chunk-ZRDXIUWC.js";import{a as y}from"./chunk-KKIQMPVP.js";import{a as s,c as Be}from"./chunk-4DUPDUSC.js";Function.prototype.toString=function(){return"[native code]"};var Bt=globalThis,ti=Bt.caches;if(ti){let n=ti.open;Bt.caches.open=function(e){let t=y.instance.deploymentName??y.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Bt.caches.default,Object.freeze(Bt.caches)}var ni=new Map,Un=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)})}},nt=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=ni.get(e);r||(r=new Un(t),ni.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 Zn="__zuplo-expiry-header",It=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(Zn);if(!i){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(i);if(Date.now()>=a){try{await t.delete(r)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),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(Zn,`${Date.now()+r*1e3}`);let i=await this.#r(),a=this.#o(e),u=new Response(JSON.stringify(t),{headers:o});await i.put(a,u)}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(Zn,`${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 ie=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new nt(r),this.#n=new It(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)}};var ri="zuplo-request-id",Ge="zp-rid",Fn="zp-body-removed",We="cf-ray",oi="x-real-ip",$n="cf-ipcity",jn="cf-ipcontinent",zn="cf-ipcountry",Bn="cf-iplongitude",Vn="cf-iplatitude",ii="cf-region",si="cf-region-code",ai="cf-metro-code",ui="cf-postal-code",ci="cf-timezone",li="zp-ipcity",di="zp-ipcontinent",pi="zp-ipcountry",mi="zp-iplongitude",gi="zp-iplatitude",fi="true-client-ip",Gn="zp-asn",Wn="zp-asorg",Kn="zp-colo",Jn="zp-postalcode",Xn="zp-metrocode",Yn="zp-region",Qn="zp-regioncode",er="zp-timezone",hi=[$n,jn,zn,Bn,Vn,Gn,Wn,Kn,Jn,Xn,Yn,Qn,er],yi=["zp-","cf-"],bi=[Ge,We,Fn];var Et=Symbol("zuplo_meters"),Vt=Symbol("zuplo_dynamic_meters"),Gt="system-logger";var os=Be(Ve());import{trace as ru}from"@opentelemetry/api";import{SpanStatusCode as Ra,trace as Pa}from"@opentelemetry/api";import{SpanStatusCode as or,trace as ir}from"@opentelemetry/api";var wi=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Ri(n){wi=n}s(Ri,"setTelemetryInitFunction");var Pi=s(n=>wi(n),"proxyHandler");var Ue=class{static{s(this,"RuntimePlugin")}},De=class extends Ue{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Wt=class extends De{static{s(this,"MeteringPlugin")}},xt=class extends Ue{static{s(this,"TelemetryPlugin")}};var Kt=new Set,Ii=new Set;function g(n){Ii.has(n)||(Ii.add(n),Kt.add(n))}s(g,"trackFeature");function Ei(){let n=[...Kt];return Kt.clear(),n}s(Ei,"getUnsentFeatures");function xi(n){for(let e of n)Kt.add(e)}s(xi,"restoreFeatures");var Tt=class n{static{s(this,"InternalProblemResponseFormatter")}static problemResponseFormat=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"}})};static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new _("Error in custom 'problemResponseFormat'",{cause:i})}})}},Ke=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Tt.problemResponseFormat(e,t,r)}};function Jt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Jt(t)}return Object.freeze(n)}s(Jt,"deepFreeze");var te=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 Jt(this.#e)}get params(){return Jt(this.#t)}user};var vt={},Me=[],tr=[],nr=[],rr=[];var Xt={addPlugin(n){Me.push(n)},addRequestHook(n){tr.push(n)},addResponseSendingHook(n){nr.push(n)},addResponseSendingFinalHook(n){rr.push(n)}},vi=s(async(n,e)=>{if(tr.length===0)return n;let t=ir.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of tr){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(o,e);if(c instanceof te||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof o}.`);throw u.end(),u.recordException(l),u.setStatus({code:or.ERROR}),l}});if(a instanceof te)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Si=s(async(n,e,t)=>{if(nr.length===0)return n;let r=ir.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of nr)await r.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)i=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof i}.`);throw u.recordException(l),u.setStatus({code:or.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),Ci=s(async(n,e,t)=>{if(rr.length===0)return;let r=ir.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of rr)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:or.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Ti=!1;async function Oi(n){if(!Ti){n&&(g("runtime.extensions"),await n(Xt)),vt.value=Xt;for(let e of Me)if(e instanceof xt){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});Ri(t)}for(let e of Me)e instanceof De&&await e.initialize(Xt);Tt.setProblemResponseFormat(Xt.problemResponseFormat),Ti=!0}}s(Oi,"initializeRuntime");var sr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function ar(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(sr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(sr.Json)||!e?JSON.stringify(n):n}s(ar,"serialize");function rt(n){return fe.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(fe.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(rt,"isSystemRoute");var le=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>Pa.getTracer("pipeline").startActiveSpan(`handler:${o.route.handler.export}`,async a=>{try{return await e(r,o)}catch(u){o.log.error("Error executing request handler.",u);let c=t.errorHandler(r,o,u);return a.setStatus({code:Ra.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async P=>{let S=a.pop();return S?S(o,i,t,u):await this.#e(async j=>{let U=await r(j,i);return Ia(U)},t)(P,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(rt(d)&&y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new St(o,l);i.dispatchEvent(p);let f=he.getContextExtensions(i),h=f.latestRequest,O;try{O=await p.mutableResponse}catch(P){return i.log.error(P),t.errorHandler(o,i,P)}try{O=await f.onResponseSending(O,h,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,i,P)}try{O=await Si(O,h,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,i,P)}i.dispatchEvent(new Ct(o,O));try{await f.onResponseSendingFinal(l,h,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Ci(l,h,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return O}};function Ia(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(ar(n),{headers:{"content-type":"application/json"}})}s(Ia,"resultToResponse");var Yt=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(Yt||{}),Ai={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 Ea={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"},ur=Ea;function xa(n){return`${new URL(n.url).pathname}`}s(xa,"instance");function Ta(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:y.instance.build.BUILD_ID},r=n.headers.get(We);return r&&(t.rayId=r),t}s(Ta,"trace");var va=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:xa(e),trace:Ta(e,t),...r},additionalHeaders:o,statusText:ur[n.status]}),"merge"),cr=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Ke.format(e,t,r):Ke.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Ai[e],...t}}},x=class extends cr{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=va(this.getProblemFromStatus(e),t,r,o,i);return Ke.format(a,t,r)}static continue=(e,t,r,o)=>this.#e(200,e,t,r,o);static switchingProtocols=(e,t,r,o)=>this.#e(101,e,t,r,o);static processing=(e,t,r,o)=>this.#e(102,e,t,r,o);static earlyHints=(e,t,r,o)=>this.#e(103,e,t,r,o);static ok=(e,t,r,o)=>this.#e(200,e,t,r,o);static created=(e,t,r,o)=>this.#e(201,e,t,r,o);static accepted=(e,t,r,o)=>this.#e(202,e,t,r,o);static nonAuthoritativeInformation=(e,t,r,o)=>this.#e(203,e,t,r,o);static noContent=(e,t,r,o)=>this.#e(204,e,t,r,o);static resetContent=(e,t,r,o)=>this.#e(205,e,t,r,o);static partialContent=(e,t,r,o)=>this.#e(206,e,t,r,o);static multiStatus=(e,t,r,o)=>this.#e(207,e,t,r,o);static alreadyReported=(e,t,r,o)=>this.#e(208,e,t,r,o);static imUsed=(e,t,r,o)=>this.#e(226,e,t,r,o);static multipleChoices=(e,t,r,o)=>this.#e(300,e,t,r,o);static movedPermanently=(e,t,r,o)=>this.#e(301,e,t,r,o);static found=(e,t,r,o)=>this.#e(302,e,t,r,o);static seeOther=(e,t,r,o)=>this.#e(303,e,t,r,o);static notModified=(e,t,r,o)=>this.#e(304,e,t,r,o);static useProxy=(e,t,r,o)=>this.#e(305,e,t,r,o);static switchProxy=(e,t,r,o)=>this.#e(306,e,t,r,o);static temporaryRedirect=(e,t,r,o)=>this.#e(307,e,t,r,o);static permanentRedirect=(e,t,r,o)=>this.#e(308,e,t,r,o);static badRequest=(e,t,r,o)=>this.#e(400,e,t,r,o);static unauthorized=(e,t,r,o)=>this.#e(401,e,t,r,o);static paymentRequired=(e,t,r,o)=>this.#e(402,e,t,r,o);static forbidden=(e,t,r,o)=>this.#e(403,e,t,r,o);static notFound=(e,t,r,o)=>this.#e(404,e,t,r,o);static methodNotAllowed=(e,t,r,o)=>this.#e(405,e,t,r,o);static notAcceptable=(e,t,r,o)=>this.#e(406,e,t,r,o);static proxyAuthenticationRequired=(e,t,r,o)=>this.#e(407,e,t,r,o);static requestTimeout=(e,t,r,o)=>this.#e(408,e,t,r,o);static conflict=(e,t,r,o)=>this.#e(409,e,t,r,o);static gone=(e,t,r,o)=>this.#e(410,e,t,r,o);static lengthRequired=(e,t,r,o)=>this.#e(411,e,t,r,o);static preconditionFailed=(e,t,r,o)=>this.#e(412,e,t,r,o);static contentTooLarge=(e,t,r,o)=>this.#e(413,e,t,r,o);static uriTooLong=(e,t,r,o)=>this.#e(414,e,t,r,o);static unsupportedMediaType=(e,t,r,o)=>this.#e(415,e,t,r,o);static rangeNotSatisfiable=(e,t,r,o)=>this.#e(416,e,t,r,o);static expectationFailed=(e,t,r,o)=>this.#e(417,e,t,r,o);static imATeapot=(e,t,r,o)=>this.#e(418,e,t,r,o);static misdirectedRequest=(e,t,r,o)=>this.#e(421,e,t,r,o);static unprocessableContent=(e,t,r,o)=>this.#e(422,e,t,r,o);static locked=(e,t,r,o)=>this.#e(423,e,t,r,o);static failedDependency=(e,t,r,o)=>this.#e(424,e,t,r,o);static tooEarly=(e,t,r,o)=>this.#e(425,e,t,r,o);static upgradeRequired=(e,t,r,o)=>this.#e(426,e,t,r,o);static preconditionRequired=(e,t,r,o)=>this.#e(428,e,t,r,o);static tooManyRequests=(e,t,r,o)=>this.#e(429,e,t,r,o);static requestHeaderFieldsTooLarge=(e,t,r,o)=>this.#e(431,e,t,r,o);static unavailableForLegalReasons=(e,t,r,o)=>this.#e(451,e,t,r,o);static internalServerError=(e,t,r,o)=>this.#e(500,e,t,r,o);static notImplemented=(e,t,r,o)=>this.#e(501,e,t,r,o);static badGateway=(e,t,r,o)=>this.#e(502,e,t,r,o);static serviceUnavailable=(e,t,r,o)=>this.#e(503,e,t,r,o);static gatewayTimeout=(e,t,r,o)=>this.#e(504,e,t,r,o);static httpVersionNotSupported=(e,t,r,o)=>this.#e(505,e,t,r,o);static variantAlsoNegotiates=(e,t,r,o)=>this.#e(506,e,t,r,o);static insufficientStorage=(e,t,r,o)=>this.#e(507,e,t,r,o);static loopDetected=(e,t,r,o)=>this.#e(508,e,t,r,o);static notExtended=(e,t,r,o)=>this.#e(510,e,t,r,o);static networkAuthenticationRequired=(e,t,r,o)=>this.#e(511,e,t,r,o)};var Ze=class extends Ue{static{s(this,"MetricsPlugin")}};var X=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 W(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var J=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=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)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};var Qt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=y.instance.loggingId,this.#e=e,this.#t=new J("ellie-metrics-transport",10,this.dispatchFunction,X.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:r}=y.instance,{ACCOUNT_NAME:o,PROJECT_NAME:i}=y.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=Ei(),c={metadata:{timestamp:new Date,accountName:o,projectName:i,deploymentName:r},metrics:a,features:u},l=await F.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":y.instance.deploymentName??"unknown","user-agent":y.instance.systemUserAgent}});if(!l.ok){let d=await l.text();X.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),xi(u)}}};var se=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.version=Ot.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Ot={name:"__system-no-version",pathPrefix:""};var ye=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get(We)??void 0,c=n.headers.get(fi)??void 0,l=e.incomingRequestProperties,d;e.route instanceof se&&(d=e.route.systemRouteName);let p=he.getContextExtensions(e).latestRequest,f={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,requestId:e.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:u,instanceId:y.instance.instanceId,userSub:p.user?.sub,clientIp:c},h=[];return h.push(new Qt(e)),Me.forEach(O=>{if(O instanceof Ze){let P=O.getTransport();h.push(P)}}),h.forEach(O=>{O.pushMetrics(f,e)}),a},"metricsProcessor");var lr=s((n,e)=>{let t=s(async(i,a)=>{let c=new URL(i.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(i,a);let l=y.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=i.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&X.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new le({processors:[ye],handler:t,gateway:e}),o=new se({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:Sa}=Object.prototype,{propertyIsEnumerable:Ca}=Object.prototype;function dr(n){return Sa.call(n)}s(dr,"toString");function Ie(n){return typeof n=="string"}s(Ie,"isString");function ot(n){return Ie(n)&&n!==""}s(ot,"isNonEmptyString");function Li(n){return dr(n)==="[object RegExp]"}s(Li,"isRegexp");function ki(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Ca.call(n,e))]}s(ki,"getOwnEnumerableKeys");function Je(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Je,"isObject");function pr(n){return typeof n=="number"&&!isNaN(n)}s(pr,"isNumber");function mr(n){return n===!0||n===!1}s(mr,"isBoolean");function _i(n){return typeof n>"u"}s(_i,"isUndefined");function Ni(n){return _i(n)||n===null}s(Ni,"isUndefinedOrNull");function At(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(At,"isErrorLike");var Di=new Map;function it(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 Error("Malformed input string");let e=Di.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),u=parseInt(i[1],10);for(let c=a;c<=u;c++)r.push(c)}else r.push(parseInt(o,10))}return Di.set(n,r),r}s(it,"statusCodesStringToNumberArray");function Xe(n,e,t){if(!e.startsWith("."))throw new m(`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 _(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Xe,"getValueFromRequestUser");function Ye(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Ie(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}s(Ye,"parseValueToStringArray");function Mi(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!Je(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ot(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!pr(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!mr(t.allowCredentials))throw new m("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=gr(t,"allowedHeaders"),o=gr(t,"allowedMethods"),i=gr(t,"exposeHeaders"),a;try{a=Ye(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.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(Mi,"parseCorsPolicies");function gr(n,e){let t;if(n[e]!==void 0)try{t=Ye(n[e])}catch(r){throw new m(`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(gr,"parseOptionalProperty");var en=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"),tn=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 fr=s((n,e)=>{let t=e.routeData.corsPolicies,r=s(async(a,u)=>{let c=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 x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let f=n.lookup(l,c);if(!f)return x.notFound(a,u);let h=f.routeConfiguration,O=Oa(l,d,p,h,t);return O.isValid?new Response(void 0,{status:200,statusText:"OK",headers:O.headers}):(O.error&&u.log.warn(O.error),x.notFound(a,u))},"optionsHandler"),o=new le({processors:[ye],handler:r,gateway:e}),i=new se({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),Oa=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 m(`Invalid Configuration - corsPolicy '${r.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=en(a.allowedOrigins,t);return u?{isValid:!0,headers:tn(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Hi=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 le({processors:[ye],handler:t,gateway:e}),o=new se({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 hr=new se({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),qi=s((n,e)=>{let t=s(async(o,i)=>{let a=vt.value?.notFoundHandler;if(a){let u=he.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,i)},"notFoundHandler"),r=new le({processors:[ye],handler:t,gateway:e});n.addRoute(hr,r.execute)},"registerNotMatchedHandler");var Aa=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Ui=s(n=>{Aa.forEach(e=>n.delete(e))},"stripCorsHeaders"),nn=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 Ui(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 W(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=La(o,t.routeData.corsPolicies),u=ka(n,a),c=new Headers(i.headers);return Ui(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(i.body,{status:i.status,statusText:i.statusText,headers:c,webSocket:i.webSocket})},"corsProcessor"),La=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 m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),ka=s((n,e)=>{let t=en(e.allowedOrigins,n.headers.get("origin"));return t?tn(e,t):{}},"getCorsHeaders");var yr=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 le({processors:[nn],handler:t,gateway:e}),o=new se({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as Zi,trace as Fi}from"@opentelemetry/api";var Le={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 rn=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ie(t))throw new _(`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}},de=class extends rn{static{s(this,"InboundPolicy")}},Fe=class extends rn{static{s(this,"OutboundPolicy")}};var Rr=class extends de{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)}},Pr=class extends Fe{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)}},br=new Map;function Lt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!br.has(i)).forEach(i=>{let a=e?.find(l=>l.name===i);if(!a)throw new m(`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 m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof module '${typeof u}')`);if(u.prototype instanceof de)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Rr(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${i}' on route '${r}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${i}' on route '${r}' (typeof handler '${typeof c.handler}')`);br.set(a.name,c)}),t.map(i=>{let a=br.get(i);if(a===void 0)throw new _("Internal error. Policy not found in cache.");return a})}s(Lt,"getInboundPolicyInstances");var wr=new Map;function _a(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!wr.has(o)).forEach(o=>{let i=e?.find(c=>c.name===o);if(!i)throw new m(`Invalid state - no Policy with the name '${o}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof i.handler?.module!="object")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof i.handler?.module}')`);let a=i.handler?.module[i.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof Fe)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new Pr(a,i.handler.options??{},i.name);else throw new m(`Invalid state - invalid policy '${o}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${o}' on route '${n.path}'`);wr.set(i.name,u)}),t.map(o=>{let i=wr.get(o);if(i===void 0)throw new _("Internal error. Policy not found in cache.");return i})}s(_a,"getOutboundPolicyInstances");var Ir=s(n=>async(e,t)=>{let r=he.getContextExtensions(t),o=Fi.getTracer("pipeline");return await o.startActiveSpan("policies:inbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof te||p instanceof Response)return d.end(),p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Zi.ERROR}),d.recordException(f),f}});if(l instanceof te)u=l;else if(l instanceof Request)u=new te(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),Na=s(n=>async(e,t,r)=>{let o=Fi.getTracer("pipeline");return await o.startActiveSpan("policies:outbound",async i=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await o.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Le.PolicyName,c.policyName),d.setAttribute(Le.PolicyType,c.policyType);let p=await c.handler(u,t,r);if(p instanceof Response)return p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${r.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Zi.ERROR}),d.recordException(f),f}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),on=s(async(n,e,t,r)=>{let o=Lt(e.route,t.routeData.policies),i=_a(e.route,t.routeData.policies);return ji({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function $i({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>ji({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s($i,"createInternalPolicyProcessor");async function ji({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=Ir(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=Na(r),d;return y.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),o.errorHandler(n,e,u)}}s(ji,"executePolicyProcessor");function zi(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||Da,i=0;for(;i<n.length;){let a=n.indexOf("=",i);if(a===-1)break;let u=n.indexOf(";",i);if(u===-1)u=n.length;else if(u<a){i=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(i,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Ma(l,o)}i=u+1}return t}s(zi,"parse");function Da(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(Da,"decode");function Ma(n,e){try{return e(n)}catch{return n}}s(Ma,"tryDecode");function Bi(n,e){try{let t=/v\d+(-\d+)?/g,o=zi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(Bi,"devPortalBaseURL");var Vi="/__zuplo/dev-portal",Ha="dev-portal-id",qa="dev-portal-host",Ua="zp-account",Za="zp-project",Fa="dev-portal-build",$a=`
26
26
  <!DOCTYPE html>
27
27
  <html lang="en">
28
28
  <head>
@@ -36,20 +36,20 @@ import{a as Ue,d as be,e as ua,f as _n,g as Nn,h as ca,i as la}from"./chunk-FYAU
36
36
  <p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
37
37
  </body>
38
38
  </html>
39
- `,$i=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=y.instance.deploymentName,o=y.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(y.instance.isLocalDevelopment)return new Response(_a,{headers:{"content-type":"text/html"}});if(!r)return T.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=qi(o,c.headers),g=new URL(`${d.pathname}${d.search}`,p),{headers:f,method:O,body:P}=c;return y.instance.build.ACCOUNT_NAME&&f.set(Aa,y.instance.build.ACCOUNT_NAME),y.instance.build.PROJECT_NAME&&f.set(La,y.instance.build.PROJECT_NAME),f.set(Ca,r),f.set(Oa,d.host),f.set(ka,y.instance.build.BUILD_ID),await $.fetch(g.toString(),{headers:f,method:O,body:P,redirect:"manual"})},"devPortalRoute"),a=new ce({processors:[fe,tn],handler:i,gateway:e}),u=new ie({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(u,a.execute)},"registerDevPortalV3Route"),ji=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=s(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring(Fi.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new ce({processors:[fe],handler:r,gateway:e}),i=new ie({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Fi}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var Ji=ze(Ve());var wr=0,Lt=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=e=>{let t=["error","warn","info","debug"],r=!1,o=s(()=>{},"emptyFunction"),i=s((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:i,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,t,r,o,i,a){wr>=Number.MAX_SAFE_INTEGER&&(wr=0);let u={requestId:r,rayId:o,level:e,logSource:t,messages:i,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:wr++};this.#t[e](u,a)}};var le=class extends Ze{static{s(this,"LogPlugin")}};var nn=class{static{s(this,"LoggingContext")}constructor(e,t,r){this.#e=e,this.custom=t,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var kt=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=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var Na=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Da=new Map(Na);var Ma=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Rr=Symbol(".toJSON was called"),Ha=s(n=>{n[Rr]=!0;let e=n.toJSON();return delete n[Rr],e},"toJSON"),Ua=s(n=>Da.get(n)??Error,"getErrorConstructor"),Bi=s(({from:n,seen:e,to:t,forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(n))t=[];else if(!u&&Ot(n)){let l=Ua(n.name);t=new l}else t={};if(e.push(n),i>=o)return t;if(a&&typeof n.toJSON=="function"&&n[Rr]!==!0)return Ha(n);let c=s(l=>Bi({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u}),"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]=c(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:d}of Ma)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Ot(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function we(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Bi({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}s(we,"serializeError");var Za=/file:\/\/\/(.*?)\/dist\//g,qa="at async Event.respondWith";function zi(n){return typeof n!="string"?n:n.split(`
40
- `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(Za,"").replaceAll(qa,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
41
- `)}s(zi,"cleanStack");function rn(n,e,t=""){let r=[],o=e?.maxDepth??3;return s(function i(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
39
+ `,Gi=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=y.instance.deploymentName,o=y.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(y.instance.isLocalDevelopment)return new Response($a,{headers:{"content-type":"text/html"}});if(!r)return x.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=Bi(o,c.headers),f=new URL(`${d.pathname}${d.search}`,p),{headers:h,method:O,body:P}=c;return y.instance.build.ACCOUNT_NAME&&h.set(Ua,y.instance.build.ACCOUNT_NAME),y.instance.build.PROJECT_NAME&&h.set(Za,y.instance.build.PROJECT_NAME),h.set(Ha,r),h.set(qa,d.host),h.set(Fa,y.instance.build.BUILD_ID),await F.fetch(f.toString(),{headers:h,method:O,body:P,redirect:"manual"})},"devPortalRoute"),a=new le({processors:[ye,on],handler:i,gateway:e}),u=new se({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${t}|/_next)(.*)`,systemRouteName:"developer-portal"});n.addRoute(u,a.execute)},"registerDevPortalV3Route"),Wi=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=s(async a=>{let u=new URL(a.url);return u.pathname=`${t}${u.pathname.substring(Vi.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new le({processors:[ye],handler:r,gateway:e}),i=new se({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Vi}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var ts=Be(Ve());var Er=0,kt=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=e=>{let t=["error","warn","info","debug"],r=!1,o=s(()=>{},"emptyFunction"),i=s((a,u)=>{this.#i.forEach(c=>{c.log(a,u)})},"pushFunction");t.forEach(a=>{this.#t[a]=r?o:i,a==e&&(r=!0)})};#t={};#n;#r;#o;#i;log(e,t,r,o,i,a){Er>=Number.MAX_SAFE_INTEGER&&(Er=0);let u={requestId:r,rayId:o,level:e,logSource:t,messages:i,timestamp:new Date,logOwner:this.#n,loggingId:this.#r,buildId:this.#o,vectorClock:Er++};this.#t[e](u,a)}};var pe=class extends Ue{static{s(this,"LogPlugin")}};var sn=class{static{s(this,"LoggingContext")}constructor(e,t,r){this.#e=e,this.custom=t,this.originalRequest=r}#e;custom;originalRequest;waitUntil=e=>{this.#e.waitUntil(e)}};var _t=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=(...e)=>{this.#r.log("debug",this.#e,this.#t,this.#n,e,this.#o)};info=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};log=(...e)=>{this.#r.log("info",this.#e,this.#t,this.#n,e,this.#o)};warn=(...e)=>{this.#r.log("warn",this.#e,this.#t,this.#n,e,this.#o)};error=(...e)=>{this.#r.log("error",this.#e,this.#t,this.#n,e,this.#o)}};var ja=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),za=new Map(ja);var Ba=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],xr=Symbol(".toJSON was called"),Va=s(n=>{n[xr]=!0;let e=n.toJSON();return delete n[xr],e},"toJSON"),Ga=s(n=>za.get(n)??Error,"getErrorConstructor"),Ki=s(({from:n,seen:e,to:t,forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u})=>{if(!t)if(Array.isArray(n))t=[];else if(!u&&At(n)){let l=Ga(n.name);t=new l}else t={};if(e.push(n),i>=o)return t;if(a&&typeof n.toJSON=="function"&&n[xr]!==!0)return Va(n);let c=s(l=>Ki({from:l,seen:[...e],forceEnumerable:r,maxDepth:o,depth:i,useToJSON:a,serialize:u}),"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]=c(n[l]);continue}t[l]="[Circular]"}}for(let{property:l,enumerable:d}of Ba)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:At(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function Re(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Ki({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}s(Re,"serializeError");var Wa=/file:\/\/\/(.*?)\/dist\//g,Ka="at async Event.respondWith";function Ji(n){return typeof n!="string"?n:n.split(`
40
+ `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(Wa,"").replaceAll(Ka,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
41
+ `)}s(Ji,"cleanStack");function an(n,e,t=""){let r=[],o=e?.maxDepth??3;return s(function i(a,u={},c,l){let d=u.indent||" ",p;u.inlineCharacterLimit===void 0?p={newline:`
42
42
  `,newlineOrSpace:`
43
- `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let g=s(f=>{if(u.inlineCharacterLimit===void 0)return f;let O=f.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return O.length<=u.inlineCharacterLimit?O:f.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
44
- `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||vi(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 f="["+p.newline+a.map((O,P)=>{let S=a.length-1===P?p.newline:","+p.newlineOrSpace,H=i(O,u,c+d,l+1);return u.transform&&(H=u.transform(a,P,H)),p.indent+H+S}).join("")+p.pad+"]";return r.pop(),g(f)}if(Je(a)){let f=Si(a);if(u.filter&&(f=f.filter(P=>u.filter?.(a,P))),f.length===0)return"{}";r.push(a);let O="{"+p.newline+f.map((P,S)=>{let H=f.length-1===S?p.newline:","+p.newlineOrSpace,k=typeof P=="symbol",j=!k&&/^[a-z$_][$\w]*$/i.test(P),Z=k||j?P:i(P,u,"",l+1),F=i(a[P],u,c+d,l+1);return u.transform&&(F=u.transform(a,P,F)),p.indent+String(Z)+": "+F+H}).join("")+p.pad+"}";return r.pop(),g(O)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,f=>f===`
45
- `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}s(rn,"stringifyObject");function $e(n){return n.map(e=>we(e))}s($e,"makeErrorsSerializable");function st(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:He(we(e))}s(st,"extractBestMessage");function Vi(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Ot(t))if(t.stack)e.push(t.stack);else{let r=rn(we(t));e.push(r)}else if(typeof t=="object"){let r=rn(t);e.push(r)}else{let r=Pr(t);e.push(r)}}),e.join(`
46
- `)}s(Vi,"messagesToMultilineText");function He(n){return typeof n=="string"?n:JSON.stringify(n)}s(He,"stringifyNonString");function Pr(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"?ar(n):"unknown"}s(Pr,"stringifyNonStringToText");import{importPKCS8 as Fa,SignJWT as $a}from"jose";async function Re(n,e,t){for(let r=0;r<=n.retries;r++){let o=$.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 m("An unknown error occurred, ensure retries is not negative")}s(Re,"fetchRetry");async function ke({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new $a(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(ke,"getTokenFromGcpServiceAccount");async function Gi(n,e,t){return Wi(n,{token:e,returnSecureToken:!0},t)}s(Gi,"exchangeFirebaseJwtForIdToken");async function on(n,e,t){return Wi(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(on,"exchangeGgpJwtForIdToken");async function Wi(n,e,t){let r=await Re(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new M({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Wi,"fetchToken");var Ee=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 Fa(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 Ir=class extends le{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new _t(this.options)}},ja="https://logging.googleapis.com/v2/entries:write?alt=json",Er={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},_t=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName,h("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Ee.init(this.#e)}log(e,t){if(!this.#t)throw new K("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:$e(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:Er[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=st(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await Ee.init(this.#e));let t=await ke({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await $.fetch(ja,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new J("google-log-transport",1,this.dispatchFunction)};var sn="gcp";function an(n){let e={allMessages:$e(n.messages)},t="zuplo-production",r=st(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Er[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(an,"gcpLogFormat");var Nt=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===sn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[an(e)])}else this.#e.log(JSON.stringify(e))}};var Sr=class extends le{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new Dt(this.options)}},xr="__ddtags",Tr="__ddattr",vr=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Ba=s(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(vr(r)):t.push(`${vr(r)}:${vr(o.toString())}`)}),t.join(",")},"formatTags"),Dt=class{static{s(this,"DataDogTransport")}constructor(e){h("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}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[xr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(f=>f[xr]!==void 0);a>-1&&(Object.assign(r,i[a][xr]),i.splice(a,1));let u={},c=t.custom[Tr];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(f=>f[Tr]!==void 0);l>-1&&(Object.assign(u,i[l][Tr]),i.splice(l,1));let d=$e(i),g={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:st(d),service:e.loggingId,ddtags:Ba(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(g,u),this.batcher.enqueue(g),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await $.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new J("data-dog-transport",10,this.dispatchFunction)};var Mt=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===sn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[an(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 za=s(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await $.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:$e(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),un,cn=class{static{s(this,"RemoteLogTransport")}constructor(e){un||(un=new J("remote-log-transport",1,za(e)))}log(e,t){un.enqueue(e),t.waitUntil(un.waitUntilFlushed())}};var Va={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Ki=s((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:Va[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var Ga=s(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let i=Ki(t,r);try{await $.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),ln,dn=class{static{s(this,"UnifiedLogTransport")}constructor(e){ln||(ln=new J("unified-log-transport",1,Ga(e)))}async log(e,t){ln.enqueue(e),t.waitUntil(ln.waitUntilFlushed())}};var Cr=(0,Ji.debug)("zuplo:logging"),pn=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;Cr("Gateway.setupSystemCoreLogger");let o=[],i=t.getService(Bt);return i?o.push(new Mt(i.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Nt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new dn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new Lt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Cr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=t.getService(Bt);if(a&&a.captureUserLogs===!0?r.push(new Mt(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Nt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new cn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new _t({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Dt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Me.forEach(u=>{u instanceof le&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new Lt(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i){Cr("Gateway.createRequestLoggers");let a=new nn(r,o,i),u=new kt(e,t,this.systemCoreLogger,a);return{userRequestLogger:new kt(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var Qe=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.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var Or=class{static{s(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},Ht=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Ar=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}},Ut=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof Qe||e instanceof ie))throw new K("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(i=>i.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let i=new URLPattern({pathname:o}),a=new Or(o,i,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new Ar(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let i=r[o],u=i.urlPattern.exec({pathname:t});if(u!==null)return new Ht(i.config,i.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new Ht(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Lr;function Yi(n){Lr=n}s(Yi,"setGlobalZuploEventContext");function mn(){if(Lr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Lr}s(mn,"getGlobalZuploEventContext");function Xi({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);pi.includes(o.toLowerCase())&&!mi.includes(r.toLowerCase())&&t.delete(r)}t.delete(Qo)}else di.forEach(r=>{t.delete(r)});return t}s(Xi,"normalizeIncomingRequestHeaders");var _e=(0,Qi.debug)("zuplo:runtime"),Ka=s(n=>{let e=n.findIndex(t=>t.name===Ct.name);return e>-1?[...n.splice(e),Ct]:[...n,Ct]},"setupSystemNoVersion"),me=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;_e("Gateway.constructor"),Le,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(_e("Gateway.initialize"),!n.#e){let i=await pn.init(r),a=e(),u={...a,corsPolicies:Li(a.corsPolicies)},c=new n(u,t,i,o);n.#e=c}if(!n.#e)throw new K("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){_e("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new K("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[tn,Qt,fe];#o;setupRoutes=()=>{_e("Gateway.setupRoutes");let e=this.routeData,t=Ka(e.versions),r=new Ut(t);if(e.routes.length===0)return sr(r,this),mr(r,this),dr(r,this),ki(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(ji(r,this),$i(r,this)),sr(r,this),mr(r,this),dr(r,this);for(let i of Me)i instanceof De&&i.registerRoutes(r,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 m(`Invalid state - No handler on route for path '${i.path}'`);let u=new ce({processors:this.#r,handler:a,gateway:this}),c=new Qe(i);r.addRoute(c,u.execute)}),_i(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return _e("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){_e("Gateway.internalErrorResponse");let o={};if(y.instance.isWorkingCopy){if(r instanceof M&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=we(r.cause);"stack"in i&&(i.stack=zi(i.stack)),o={cause:i}}}return T.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:i}=t;Yi(r);let a=Xi({headers:e.headers,removeAllVendorHeadersExceptListed:y.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Ge,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let j=new Headers(u.headers);j.set(Hn,"true"),u=new Request(u,{headers:j,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,i,r,c,u),p=new URL(u.url),g=p.pathname,f=this.#n.lookup(u.method,g);if(!f)throw new K(`Invalid state - no route match - should have been picked up by the not found handler, path: '${g}'`);let O=new gn(e.headers),P=new ee(u,{params:f.params}),S=new fn({logger:l,route:f.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:O}),H=f.routeConfiguration.raw();Wa.getActiveSpan()?.setAttributes({"http.route":S.route.path??S.route.pathPattern,"cloud.region":S.incomingRequestProperties.colo,[Le.RoutePathPattern]:S.route.pathPattern,[Le.RouteOperationId]:H.operationId,[Le.RouteTrace]:H["x-zuplo-trace"],[Le.RouteSystem]:rt(p)?!0:void 0});let k=ge.initialize(S,P);if(f.routeConfiguration===pr&&Tt.value?.notFoundHandler!==void 0){let j=this.#n.lookupByPathOnly(g);k.pathOnlyMatches=j.map(Z=>Z.routeConfiguration).filter(Z=>Z instanceof Qe)}try{if(Y.addLogger(S,d),y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!rt(p):!p.pathname.startsWith("/__zuplo")){let E=await Pi(P,S);if(E instanceof Response)return E;{let D=ge.getContextExtensions(S);P=E,D.latestRequest=P}}rt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:f.routeConfiguration.path});let j=f.executableHandler;Ja(j,f,u),_e("Gateway.handleRequest - call user handler");let Z=await j(P,S);if(_e("Gateway.handleRequest - user handler"),!(Z instanceof Response))throw new M(`Invalid Response type from the request handler: ${typeof Z}`);if(Z.bodyUsed)throw new M("The response object has already been used. Return a new response instead.");let F;if(Z.headers.get(Ge)===null&&!Z.webSocket){let E=new Headers(Z.headers);E.set(Ge,o),F=new Response(Z.body,{status:Z.status,statusText:Z.statusText,headers:E,cf:Z.cf})}else F=Z;return F}catch(j){return _e("Gateway - error executing handler",j),j instanceof M?(l.error(j),d.warn(j)):d.error(j),await this.#i(P,S,j)}}};function Ja(n,e,t){if(_e("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}s(Ja,"checkHandler");var es=s(async(n,e,t)=>{let r=me.instance.routeData.policies,o=At([n],r);if(o.length===0)throw new M(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var gn=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(jn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Bn)??void 0}get city(){return this.#e.get(Un)??this.#e.get(ii)??void 0}get continent(){return this.#e.get(Zn)??this.#e.get(si)??void 0}get country(){return this.#e.get(qn)??this.#e.get(ai)??void 0}get latitude(){return this.#e.get($n)??this.#e.get(ci)??void 0}get longitude(){return this.#e.get(Fn)??this.#e.get(ui)??void 0}get colo(){return this.#e.get(zn)??void 0}get postalCode(){return this.#e.get(ri)??this.#e.get(Vn)??void 0}get metroCode(){return this.#e.get(ni)??this.#e.get(Gn)??void 0}get region(){return this.#e.get(ei)??this.#e.get(Wn)??void 0}get regionCode(){return this.#e.get(ti)??this.#e.get(Kn)??void 0}get timezone(){return this.#e.get(oi)??this.#e.get(Jn)??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}}},vt=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},St=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},ge=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 M(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let i of this.#n)o=await i(e,t,r);return o}},fn=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>es(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{ge.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{ge.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;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 he=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{AsyncLocalStorage as Ya}from"node:async_hooks";var ts={request:new Ya};var Xa="Error initializing gateway. Check your configuration for errors or contact support.",Qa="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",kr=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=async(e,t,r)=>{let o=e.headers.get(Ge)??e.headers.get(Xo)??crypto.randomUUID(),i=e.headers.get(We),a={requestId:o,rayId:i};return ts.request.run(a,async()=>{y.initialize({build:this.buildEnvironment,runtime:t});try{await xi(this.runtimeInit)}catch(c){this.handleError(c,Qa,e)}return hi(s(async(c,l)=>{let d;try{d=await me.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,Xa,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof m&&(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"}})}};var ls=ze(Ve());function eu(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 u=1,c="",i=t+1;if(n[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<n.length;){if(n[i]==="\\"){c+=n[i++]+n[i++];continue}if(n[i]===")"){if(u--,u===0){i++;break}}else if(n[i]==="("&&(u++,n[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=n[i++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=i;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}s(eu,"lexer");function _r(n,e){e===void 0&&(e={});for(var t=eu(n),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(nu(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(E){if(c<t.length&&t[c].type===E)return t[c++].value},"tryConsume"),p=s(function(E){var D=d(E);if(D!==void 0)return D;var V=t[c],G=V.type,v=V.index;throw new TypeError("Unexpected ".concat(G," at ").concat(v,", expected ").concat(E))},"mustConsume"),g=s(function(){for(var E="",D;D=d("CHAR")||d("ESCAPED_CHAR");)E+=D;return E},"consumeText");c<t.length;){var f=d("CHAR"),O=d("NAME"),P=d("PATTERN");if(O||P){var S=f||"";o.indexOf(S)===-1&&(l+=S,S=""),l&&(a.push(l),l=""),a.push({name:O||u++,prefix:S,suffix:"",pattern:P||i,modifier:d("MODIFIER")||""});continue}var H=f||d("ESCAPED_CHAR");if(H){l+=H;continue}l&&(a.push(l),l="");var k=d("OPEN");if(k){var S=g(),j=d("NAME")||"",Z=d("PATTERN")||"",F=g();p("CLOSE"),a.push({name:j||(Z?u++:""),pattern:j&&!Z?i:Z,prefix:S,suffix:F,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(_r,"parse");function ns(n,e){return tu(_r(n,e),e)}s(ns,"compile");function tu(n,e){e===void 0&&(e={});var t=ru(e),r=e.encode,o=r===void 0?function(c){return c}:r,i=e.validate,a=i===void 0?!0:i,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var g=c?c[p.name]:void 0,f=p.modifier==="?"||p.modifier==="*",O=p.modifier==="*"||p.modifier==="+";if(Array.isArray(g)){if(!O)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(g.length===0){if(f)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<g.length;P++){var S=o(g[P],p);if(a&&!u[d].test(S))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(S,'"'));l+=p.prefix+S+p.suffix}continue}if(typeof g=="string"||typeof g=="number"){var S=o(String(g),p);if(a&&!u[d].test(S))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(S,'"'));l+=p.prefix+S+p.suffix;continue}if(!f){var H=O?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(H))}}return l}}s(tu,"tokensToFunction");function nu(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(nu,"escapeString");function ru(n){return n&&n.sensitive?"":"i"}s(ru,"flags");var ss=ze(Ve());var ou=(0,ss.debug)("zuplo:runtime"),Dr=new TextEncoder,rs={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"},iu=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],at=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:u,initRetryMs:c}){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=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Mr(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){ou("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,t),a=$.fetch(o,i);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}},Mr=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:u,service:c,region:l,cache:d,datetime:p,signQuery:g,appendSessionToken:f,allHeaders:O,singleEncode:P}){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=u;let S,H;(!c||!l)&&([S,H]=su(this.url,this.headers)),this.service=c||S||"",this.region=l||H||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=g,this.appendSessionToken=f||this.service==="iotdevicegateway",this.headers.delete("Host");let k=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"),k.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&k.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(Z=>O||!iu.includes(Z)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(Z=>Z+":"+(Z==="host"?this.url.host:(this.headers.get(Z)||"").replace(/\s+/g," "))).join(`
47
- `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!k.has("X-Amz-Expires")&&k.set("X-Amz-Expires","86400"),k.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),k.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),k.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,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=is(this.encodedPath);let j=new Set;this.encodedSearch=[...this.url.searchParams].filter(([Z])=>{if(!Z)return!1;if(this.service==="s3"){if(j.has(Z))return!1;j.add(Z)}return!0}).map(Z=>Z.map(F=>is(encodeURIComponent(F)))).sort(([Z,F],[E,D])=>Z<E?-1:Z>E?1:F<D?-1:F>D?1:0).map(Z=>Z.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 Zt("AWS4"+this.secretAccessKey,e),i=await Zt(o,this.region),a=await Zt(i,this.service);r=await Zt(a,"aws4_request"),this.cache.set(t,r)}return Nr(await Zt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Nr(await os(await this.canonicalString()))].join(`
43
+ `,pad:c,indent:c+d}:p={newline:"@@__STRINGIFY_OBJECT_NEW_LINE__@@",newlineOrSpace:"@@__STRINGIFY_OBJECT_NEW_LINE_OR_SPACE__@@",pad:"@@__STRINGIFY_OBJECT_PAD__@@",indent:"@@__STRINGIFY_OBJECT_INDENT__@@"};let f=s(h=>{if(u.inlineCharacterLimit===void 0)return h;let O=h.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return O.length<=u.inlineCharacterLimit?O:h.replace(new RegExp(p.newline+"|"+p.newlineOrSpace,"g"),`
44
+ `).replace(new RegExp(p.pad,"g"),c).replace(new RegExp(p.indent,"g"),c+d)},"expandWhiteSpace");if(r.includes(a))return'"[Circular]"';if(a==null||typeof a=="number"||typeof a=="boolean"||typeof a=="function"||typeof a=="symbol"||Li(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((O,P)=>{let S=a.length-1===P?p.newline:","+p.newlineOrSpace,H=i(O,u,c+d,l+1);return u.transform&&(H=u.transform(a,P,H)),p.indent+H+S}).join("")+p.pad+"]";return r.pop(),f(h)}if(Je(a)){let h=ki(a);if(u.filter&&(h=h.filter(P=>u.filter?.(a,P))),h.length===0)return"{}";r.push(a);let O="{"+p.newline+h.map((P,S)=>{let H=h.length-1===S?p.newline:","+p.newlineOrSpace,k=typeof P=="symbol",j=!k&&/^[a-z$_][$\w]*$/i.test(P),U=k||j?P:i(P,u,"",l+1),$=i(a[P],u,c+d,l+1);return u.transform&&($=u.transform(a,P,$)),p.indent+String(U)+": "+$+H}).join("")+p.pad+"}";return r.pop(),f(O)}return a=a.replace(/\\/g,"\\\\"),a=String(a).replace(/[\r\n]/g,h=>h===`
45
+ `?"\\n":"\\r"),u.singleQuotes===!1?(a=a.replace(/"/g,'\\"'),`"${a}"`):(a=a.replace(/'/g,"\\'"),`'${a}'`)},"stringify")(n,e,t,0)}s(an,"stringifyObject");function $e(n){return n.map(e=>Re(e))}s($e,"makeErrorsSerializable");function st(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:He(Re(e))}s(st,"extractBestMessage");function Xi(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(At(t))if(t.stack)e.push(t.stack);else{let r=an(Re(t));e.push(r)}else if(typeof t=="object"){let r=an(t);e.push(r)}else{let r=Tr(t);e.push(r)}}),e.join(`
46
+ `)}s(Xi,"messagesToMultilineText");function He(n){return typeof n=="string"?n:JSON.stringify(n)}s(He,"stringifyNonString");function Tr(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"?dr(n):"unknown"}s(Tr,"stringifyNonStringToText");import{importPKCS8 as Ja,SignJWT as Xa}from"jose";async function ge(n,e,t){for(let r=0;r<=n.retries;r++){let o=F.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 m("An unknown error occurred, ensure retries is not negative")}s(ge,"fetchRetry");async function ke({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new Xa(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(ke,"getTokenFromGcpServiceAccount");async function Yi(n,e,t){return Qi(n,{token:e,returnSecureToken:!0},t)}s(Yi,"exchangeFirebaseJwtForIdToken");async function un(n,e,t){return Qi(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(un,"exchangeGgpJwtForIdToken");async function Qi(n,e,t){let r=await ge(t,n,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(e)});if(r.status!==200){let i;try{let a=await r.text(),u=JSON.parse(a);i={cause:u.error??u}}catch{}throw new _({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Qi,"fetchToken");var Ee=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 Ja(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 vr=class extends pe{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Nt(this.options)}},Ya="https://logging.googleapis.com/v2/entries:write?alt=json",Sr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Nt=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=y.instance.loggingEnvironmentType,this.#i=y.instance.loggingEnvironmentStage,this.#r=y.instance.deploymentName,g("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Ee.init(this.#e)}log(e,t){if(!this.#t)throw new W("Invalid state - Google log transport is not initialized");if(e.messages.length===0)return;let r={allMessages:$e(e.messages)},o=this.#t.projectId??"zuplo-production",i={logName:this.#n,resource:{type:"global"},severity:Sr[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=st(r.allMessages);i.jsonPayload={...r,message:a},this.batcher.enqueue(i),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{if(e.length===0)return;this.#t||(this.#t=await Ee.init(this.#e));let t=await ke({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await F.fetch(Ya,{method:"POST",body:JSON.stringify({entries:e}),headers:{Authorization:`Bearer ${t}`,"content-type":"application/json;charset=UTF-8"}});r.ok||console.error(r.status,r.statusText,await r.text())};batcher=new J("google-log-transport",1,this.dispatchFunction)};var cn="gcp";function ln(n){let e={allMessages:$e(n.messages)},t="zuplo-production",r=st(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Sr[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(ln,"gcpLogFormat");var Dt=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===cn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[ln(e)])}else this.#e.log(JSON.stringify(e))}};var Lr=class extends pe{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new Mt(this.options)}},Cr="__ddtags",Or="__ddattr",Ar=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Qa=s(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Ar(r)):t.push(`${Ar(r)}:${Ar(o.toString())}`)}),t.join(",")},"formatTags"),Mt=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}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Cr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(h=>h[Cr]!==void 0);a>-1&&(Object.assign(r,i[a][Cr]),i.splice(a,1));let u={},c=t.custom[Or];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(h=>h[Or]!==void 0);l>-1&&(Object.assign(u,i[l][Or]),i.splice(l,1));let d=$e(i),f={message:{...{...e,activityId:e.requestId,trace:e.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(t.originalRequest.url).hostname,msg:st(d),service:e.loggingId,ddtags:Qa(r),environment:this.#n,environment_type:this.#r,environment_stage:this.#o};Object.assign(f,u),this.batcher.enqueue(f),t.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async e=>{e.length!==0&&await F.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new J("data-dog-transport",10,this.dispatchFunction)};var Ht=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===cn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[ln(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 eu=s(({url:n,remoteLogToken:e,loggingId:t,sendOnlyErrors:r})=>async o=>{let i;if(r===!0?i=o.filter(a=>a.level==="error"):i=o,i.length!==0)try{await F.fetch(`${n}/publish/${t}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:i.map(a=>({...a,messages:$e(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),dn,pn=class{static{s(this,"RemoteLogTransport")}constructor(e){dn||(dn=new J("remote-log-transport",1,eu(e)))}log(e,t){dn.enqueue(e),t.waitUntil(dn.waitUntilFlushed())}};var tu={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},es=s((n,e)=>t=>{let r={};return r.deploymentName=n,r.labels={requestId:t.requestId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner},r.rayId=t.rayId??"",r.runtime={buildId:e.BUILD_ID,buildTimestamp:e.TIMESTAMP,gitSHA:e.GIT_SHA,version:e.ZUPLO_VERSION},r.atomicCounter=t.vectorClock,{timestamp:t.timestamp,observerdTimestamp:t.timestamp,traceId:t.requestId,severityText:t.level,severityNumber:tu[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var nu=s(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let i=es(t,r);try{await F.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":y.instance.systemUserAgent,"zp-dn":y.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),mn,gn=class{static{s(this,"UnifiedLogTransport")}constructor(e){mn||(mn=new J("unified-log-transport",1,nu(e)))}async log(e,t){mn.enqueue(e),t.waitUntil(mn.waitUntilFlushed())}};var kr=(0,ts.debug)("zuplo:logging"),fn=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;kr("Gateway.setupSystemCoreLogger");let o=[],i=t.getService(Gt);return i?o.push(new Ht(i.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Dt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new gn({url:e.remoteLogURL,deploymentName:e.deploymentName,remoteLogToken:e.remoteLogToken,build:e.build})),await Promise.all(o.map(async a=>{a.init&&await a.init()})),new kt(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){kr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=t.getService(Gt);if(a&&a.captureUserLogs===!0?r.push(new Ht(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Dt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new pn({loggingId:e.loggingId,url:e.remoteLogURL,remoteLogToken:e.remoteLogToken,sendOnlyErrors:!e.isWorkingCopy})),o.GCP_USER_LOG_NAME&&o.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new Nt({serviceAccountJson:o.GCP_USER_LOG_SVC_ACCT_JSON,logName:o.GCP_USER_LOG_NAME})),o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let u=o.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new Mt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return Me.forEach(u=>{u instanceof pe&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new kt(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i){kr("Gateway.createRequestLoggers");let a=new sn(r,o,i),u=new _t(e,t,this.systemCoreLogger,a);return{userRequestLogger:new _t(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var Qe=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.version=e.version,this.policies=e.policies,this.excludeFromOpenApi=e.excludeFromOpenApi,this.pathPattern=e.pathPattern,e.raw?(this.#e=e.raw(),this.operationId=this.raw()?.operationId,this.summary=this.raw()?.summary,this.tags=this.raw()?.tags,this.parameters=this.raw()?.parameters,this.responses=this.raw()?.responses):(this.operationId=e.operationId,this.summary=e.summary,this.tags=e.tags,this.parameters=e.parameters,this.responses=e.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};var _r=class{static{s(this,"RouterEntry")}constructor(e,t,r,o){this.fullPath=e,this.urlPattern=t,this.config=r,this.executableHandler=o}fullPath;urlPattern;config;executableHandler},qt=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Nr=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}},Ut=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof Qe||e instanceof se))throw new W("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let r=this.versions.find(i=>i.name===e.version)?.pathPrefix,o;"pathPattern"in e&&e.pathPattern?o=`${r??""}${e.pathPattern}`:o=`${r??""}${e.path}`;try{let i=new URLPattern({pathname:o}),a=new _r(o,i,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new Nr(`addRoute-error: Invalid path '${o}'. '${i.message}'`,{cause:i})}}lookup(e,t){if(typeof e>"u")throw new m(`Invalid request - Method was undefined. Path: '${t}'`);let r=this.routeEntries.filter(o=>o.config.methods.includes(e));if(r.length!==0)for(let o=0;o<r.length;o++){let i=r[o],u=i.urlPattern.exec({pathname:t});if(u!==null)return new qt(i.config,i.executableHandler,u.pathname.groups)}}lookupByPathOnly(e){let t=[];for(let r=0;r<this.routeEntries.length;r++){let o=this.routeEntries[r],a=o.urlPattern.exec({pathname:e});if(a!==null){let u=new qt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Dr;function ns(n){Dr=n}s(ns,"setGlobalZuploEventContext");function hn(){if(Dr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Dr}s(hn,"getGlobalZuploEventContext");function rs({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);yi.includes(o.toLowerCase())&&!bi.includes(r.toLowerCase())&&t.delete(r)}t.delete(oi)}else hi.forEach(r=>{t.delete(r)});return t}s(rs,"normalizeIncomingRequestHeaders");var _e=(0,os.debug)("zuplo:runtime"),ou=s(n=>{let e=n.findIndex(t=>t.name===Ot.name);return e>-1?[...n.splice(e),Ot]:[...n,Ot]},"setupSystemNoVersion"),fe=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;_e("Gateway.constructor"),Le,this.#n=this.setupRoutes(),this.#o=this.setupErrorHandler(),this.#t=r}static{s(this,"Gateway")}static#e;static async initialize(e,t,r,o){if(_e("Gateway.initialize"),!n.#e){let i=await fn.init(r),a=e(),u={...a,corsPolicies:Mi(a.corsPolicies)},c=new n(u,t,i,o);n.#e=c}if(!n.#e)throw new W("Invalid state - Gateway not initialized after trace call. The trace provider is likely not functioning correctly.");return n.#e}static purgeGatewayCache(){_e("Gateway.purgeGatewayCache"),n.#e=void 0}static get instance(){if(!n.#e)throw new W("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[on,nn,ye];#o;setupRoutes=()=>{_e("Gateway.setupRoutes");let e=this.routeData,t=ou(e.versions),r=new Ut(t);if(e.routes.length===0)return lr(r,this),yr(r,this),fr(r,this),Hi(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Wi(r,this),Gi(r,this)),lr(r,this),yr(r,this),fr(r,this);for(let i of Me)i instanceof De&&i.registerRoutes(r,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 m(`Invalid state - No handler on route for path '${i.path}'`);let u=new le({processors:this.#r,handler:a,gateway:this}),c=new Qe(i);r.addRoute(c,u.execute)}),qi(r,this),r};setupErrorHandler=()=>{let e;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(e=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof e!="function")throw new m("Invalid state - Module and export set for 'errorHandler' is not a function")}else e=s((t,r,o)=>this.#i(t,r,o),"errorHandler");return e};errorHandler(e,t,r){try{return this.#o(e,t,r)}catch(o){return _e("An error occurred in the user's errorHandler",o),this.#i(e,t,o)}}#i(e,t,r){_e("Gateway.internalErrorResponse");let o={};if(y.instance.isWorkingCopy){if(r instanceof _&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=Re(r.cause);"stack"in i&&(i.stack=Ji(i.stack)),o={cause:i}}}return x.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:i}=t;ns(r);let a=rs({headers:e.headers,removeAllVendorHeadersExceptListed:y.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Ge,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let j=new Headers(u.headers);j.set(Fn,"true"),u=new Request(u,{headers:j,body:null})}let c={},{userRequestLogger:l,systemRequestLogger:d}=this.#t.createRequestLoggers(o,i,r,c,u),p=new URL(u.url),f=p.pathname,h=this.#n.lookup(u.method,f);if(!h)throw new W(`Invalid state - no route match - should have been picked up by the not found handler, path: '${f}'`);let O=new yn(e.headers),P=new te(u,{params:h.params}),S=new bn({logger:l,route:h.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:O}),H=h.routeConfiguration.raw();ru.getActiveSpan()?.setAttributes({"http.route":S.route.path??S.route.pathPattern,"cloud.region":S.incomingRequestProperties.colo,[Le.RoutePathPattern]:S.route.pathPattern,[Le.RouteOperationId]:H.operationId,[Le.RouteTrace]:H["x-zuplo-trace"],[Le.RouteSystem]:rt(p)?!0:void 0});let k=he.initialize(S,P);if(h.routeConfiguration===hr&&vt.value?.notFoundHandler!==void 0){let j=this.#n.lookupByPathOnly(f);k.pathOnlyMatches=j.map(U=>U.routeConfiguration).filter(U=>U instanceof Qe)}try{if(X.addLogger(S,d),y.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!rt(p):!p.pathname.startsWith("/__zuplo")){let E=await vi(P,S);if(E instanceof Response)return E;{let M=he.getContextExtensions(S);P=E,M.latestRequest=P}}rt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:h.routeConfiguration.path});let j=h.executableHandler;iu(j,h,u),_e("Gateway.handleRequest - call user handler");let U=await j(P,S);if(_e("Gateway.handleRequest - user handler"),!(U instanceof Response))throw new _(`Invalid Response type from the request handler: ${typeof U}`);if(U.bodyUsed)throw new _("The response object has already been used. Return a new response instead.");let $;if(U.headers.get(Ge)===null&&!U.webSocket){let E=new Headers(U.headers);E.set(Ge,o),$=new Response(U.body,{status:U.status,statusText:U.statusText,headers:E,cf:U.cf})}else $=U;return $}catch(j){return _e("Gateway - error executing handler",j),j instanceof _?(l.error(j),d.warn(j)):d.error(j),await this.#i(P,S,j)}}};function iu(n,e,t){if(_e("Gateway.checkHandler"),!n)throw typeof e.routeConfiguration>"u"?new m(`Invalid state - no routeConfiguration for '${t.method}:${t.url}`):new m(`Invalid state. No handler for request '${t.method}':'${e.routeConfiguration.path}'`)}s(iu,"checkHandler");var is=s(async(n,e,t)=>{let r=fe.instance.routeData.policies,o=Lt([n],r);if(o.length===0)throw new _(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var yn=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Gn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Wn)??void 0}get city(){return this.#e.get($n)??this.#e.get(li)??void 0}get continent(){return this.#e.get(jn)??this.#e.get(di)??void 0}get country(){return this.#e.get(zn)??this.#e.get(pi)??void 0}get latitude(){return this.#e.get(Vn)??this.#e.get(gi)??void 0}get longitude(){return this.#e.get(Bn)??this.#e.get(mi)??void 0}get colo(){return this.#e.get(Kn)??void 0}get postalCode(){return this.#e.get(ui)??this.#e.get(Jn)??void 0}get metroCode(){return this.#e.get(ai)??this.#e.get(Xn)??void 0}get region(){return this.#e.get(ii)??this.#e.get(Yn)??void 0}get regionCode(){return this.#e.get(si)??this.#e.get(Qn)??void 0}get timezone(){return this.#e.get(ci)??this.#e.get(er)??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}}},St=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Ct=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},he=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 _(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;pathOnlyMatches;#t;#n;constructor(e){this.latestRequest=e,this.#t=[],this.#n=[]}addResponseSendingHook(e){this.#n.push(e)}addResponseSendingFinalHook(e){this.#t.push(e)}onResponseSendingFinal=async(e,t,r)=>{for(let o of this.#t)await o(e,t,r)};onResponseSending=async(e,t,r)=>{let o=e;for(let i of this.#n)o=await i(e,t,r);return o}},bn=class extends EventTarget{static{s(this,"SystemZuploContext")}constructor({logger:e,route:t,requestId:r,event:o,custom:i,incomingRequestProperties:a}){super(),this.log=Object.freeze(e),this.route=t,this.requestId=r,this.custom=i,this.incomingRequestProperties=a,this.#e=o,this.invokeInboundPolicy=(u,c)=>is(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{he.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{he.getContextExtensions(this).addResponseSendingFinalHook(u)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;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 me=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{AsyncLocalStorage as su}from"node:async_hooks";var ss={request:new su};var au="Error initializing gateway. Check your configuration for errors or contact support.",uu="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Mr=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=async(e,t,r)=>{let o=e.headers.get(Ge)??e.headers.get(ri)??crypto.randomUUID(),i=e.headers.get(We),a={requestId:o,rayId:i};return ss.request.run(a,async()=>{y.initialize({build:this.buildEnvironment,runtime:t});try{await Oi(this.runtimeInit)}catch(c){this.handleError(c,uu,e)}return Pi(s(async(c,l)=>{let d;try{d=await fe.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,au,c)}return d.handleRequest(c,a,l)},"innerHandler"))(e,r)})};handleError(e,t,r){console.error("Error initializing gateway.",e),e instanceof m&&(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"}})}};var fs=Be(Ve());function cu(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 u=1,c="",i=t+1;if(n[i]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(i));for(;i<n.length;){if(n[i]==="\\"){c+=n[i++]+n[i++];continue}if(n[i]===")"){if(u--,u===0){i++;break}}else if(n[i]==="("&&(u++,n[i+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(i));c+=n[i++]}if(u)throw new TypeError("Unbalanced pattern at ".concat(t));if(!c)throw new TypeError("Missing pattern at ".concat(t));e.push({type:"PATTERN",index:t,value:c}),t=i;continue}e.push({type:"CHAR",index:t,value:n[t++]})}return e.push({type:"END",index:t,value:""}),e}s(cu,"lexer");function Hr(n,e){e===void 0&&(e={});for(var t=cu(n),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(du(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(E){if(c<t.length&&t[c].type===E)return t[c++].value},"tryConsume"),p=s(function(E){var M=d(E);if(M!==void 0)return M;var V=t[c],G=V.type,v=V.index;throw new TypeError("Unexpected ".concat(G," at ").concat(v,", expected ").concat(E))},"mustConsume"),f=s(function(){for(var E="",M;M=d("CHAR")||d("ESCAPED_CHAR");)E+=M;return E},"consumeText");c<t.length;){var h=d("CHAR"),O=d("NAME"),P=d("PATTERN");if(O||P){var S=h||"";o.indexOf(S)===-1&&(l+=S,S=""),l&&(a.push(l),l=""),a.push({name:O||u++,prefix:S,suffix:"",pattern:P||i,modifier:d("MODIFIER")||""});continue}var H=h||d("ESCAPED_CHAR");if(H){l+=H;continue}l&&(a.push(l),l="");var k=d("OPEN");if(k){var S=f(),j=d("NAME")||"",U=d("PATTERN")||"",$=f();p("CLOSE"),a.push({name:j||(U?u++:""),pattern:j&&!U?i:U,prefix:S,suffix:$,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(Hr,"parse");function as(n,e){return lu(Hr(n,e),e)}s(as,"compile");function lu(n,e){e===void 0&&(e={});var t=pu(e),r=e.encode,o=r===void 0?function(c){return c}:r,i=e.validate,a=i===void 0?!0:i,u=n.map(function(c){if(typeof c=="object")return new RegExp("^(?:".concat(c.pattern,")$"),t)});return function(c){for(var l="",d=0;d<n.length;d++){var p=n[d];if(typeof p=="string"){l+=p;continue}var f=c?c[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",O=p.modifier==="*"||p.modifier==="+";if(Array.isArray(f)){if(!O)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(f.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var P=0;P<f.length;P++){var S=o(f[P],p);if(a&&!u[d].test(S))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(S,'"'));l+=p.prefix+S+p.suffix}continue}if(typeof f=="string"||typeof f=="number"){var S=o(String(f),p);if(a&&!u[d].test(S))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(S,'"'));l+=p.prefix+S+p.suffix;continue}if(!h){var H=O?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(H))}}return l}}s(lu,"tokensToFunction");function du(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(du,"escapeString");function pu(n){return n&&n.sensitive?"":"i"}s(pu,"flags");var ds=Be(Ve());var mu=(0,ds.debug)("zuplo:runtime"),Ur=new TextEncoder,us={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"},gu=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],at=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:u,initRetryMs:c}){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=u??0,this.initRetryMs=c||50}async sign(e,t){let r=new Zr(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){mu("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,t),a=F.fetch(o,i);if(r===this.retries)return a;let u=await a;if(u.status<500&&u.status!==429)return u;await new Promise(c=>setTimeout(c,Math.random()*this.initRetryMs*Math.pow(2,r)))}throw new m("An unknown error occurred, ensure retries is not negative")}},Zr=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:u,service:c,region:l,cache:d,datetime:p,signQuery:f,appendSessionToken:h,allHeaders:O,singleEncode:P}){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=u;let S,H;(!c||!l)&&([S,H]=fu(this.url,this.headers)),this.service=c||S||"",this.region=l||H||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=f,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let k=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"),k.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&k.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(U=>O||!gu.includes(U)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(U=>U+":"+(U==="host"?this.url.host:(this.headers.get(U)||"").replace(/\s+/g," "))).join(`
47
+ `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!k.has("X-Amz-Expires")&&k.set("X-Amz-Expires","86400"),k.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),k.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),k.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,"/");P||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=ls(this.encodedPath);let j=new Set;this.encodedSearch=[...this.url.searchParams].filter(([U])=>{if(!U)return!1;if(this.service==="s3"){if(j.has(U))return!1;j.add(U)}return!0}).map(U=>U.map($=>ls(encodeURIComponent($)))).sort(([U,$],[E,M])=>U<E?-1:U>E?1:$<M?-1:$>M?1:0).map(U=>U.join("=")).join("&")}async sign(){return this.signQuery?(this.url.searchParams.set("X-Amz-Signature",await this.signature()),this.sessionToken&&this.appendSessionToken&&this.url.searchParams.set("X-Amz-Security-Token",this.sessionToken)):this.headers.set("Authorization",await this.authHeader()),{method:this.method,url:this.url,headers:this.headers,body:this.body}}async authHeader(){return["AWS4-HMAC-SHA256 Credential="+this.accessKeyId+"/"+this.credentialString,"SignedHeaders="+this.signedHeaders,"Signature="+await this.signature()].join(", ")}async signature(){let e=this.datetime.slice(0,8),t=[this.secretAccessKey,e,this.region,this.service].join(),r=this.cache.get(t);if(!r){let o=await Zt("AWS4"+this.secretAccessKey,e),i=await Zt(o,this.region),a=await Zt(i,this.service);r=await Zt(a,"aws4_request"),this.cache.set(t,r)}return qr(await Zt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,qr(await cs(await this.canonicalString()))].join(`
48
48
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
49
49
  `,this.signedHeaders,await this.hexBodyHash()].join(`
50
- `)}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 M("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Nr(await os(this.body||""))}return e}};async function Zt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Dr.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Dr.encode(e))}s(Zt,"hmac");async function os(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Dr.encode(n):n)}s(os,"hash");function Nr(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Nr,"buf2hex");function is(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(is,"encodeRfc3986");function su(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 u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="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 rs?[rs[i],a]:[i,a]}s(su,"guessServiceRegion");function au(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(au,"b64ToUint6");function as(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,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=au(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(as,"base64Decode");function hn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(hn,"uint6ToB64");function us(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(hn(o>>>18&63),hn(o>>>12&63),hn(o>>>6&63),hn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(us,"base64Encode");function ut(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(ut,"numberToString");function uu(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=ut(Math.floor(t/60)),i=ut(t%60);return`${r}${o}${i}`}s(uu,"getCLFOffset");function Hr(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=ut(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),i=ut(n.getHours()),a=ut(n.getMinutes()),u=ut(n.getSeconds()),c=uu(n);return`${t}/${r}/${o}:${i}:${a}:${u} ${c}`}s(Hr,"toCLFDate");var cs=(0,ls.debug)("zuplo:runtime"),cu="X-Amzn-Trace-Id",lu="x-amzn-errortype",ds=[],du=s(async(n,e,t)=>{let r=t;for await(let o of ds)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),xe=class extends M{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(cu)??void 0,this.errorType=t.get(lu)??void 0}},pu={addSendingAwsLambdaEventHook:n=>{ds.push(n)}};async function mu(n,e){h("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!r)throw new m("secretAccessKey is not set in the handler options");if(!o)throw new m("region is not set in the handler options");if(!i)throw new m("functionName is not set in the handler options");let l=new at({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(cs(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,g]=await yu(n,{binaryMediaTypes:c}),{options:f}=e.route.handler,O;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?O=hu(n,e):O=await fu(n,e,{useAwsResourcePathStyle:u}),cs("Calling onSendingAwsLambdaEvent hook");let P=await du(n,e,O);P.body=p,P.isBase64Encoded=g;let S=await l.fetch(d,{body:JSON.stringify(P)});try{return gu(S)}catch(H){if(H instanceof xe){let k=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&f.returnAmazonTraceIdHeader&&H.traceId?{AMZN_TRACE_ID_HEADER:H.traceId}:void 0;return T.internalServerError(n,e,void 0,k)}throw H}}s(mu,"awsLambdaHandler");async function gu(n){let e;try{e=await n.json()}catch{throw new xe("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 xe(e.message,n.headers):new xe(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new xe(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 xe(`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 xe(`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 xe(`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 xe("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new xe("Response was set to base64 encoded but body was not a string",n.headers);r=as(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 xe(`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(gu,"getResponse");async function fu(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]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.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:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Hr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:wu(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(fu,"buildEventVersion1");function hu(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:Hr(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(hu,"buildEventVersion2");async function yu(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&&bu(e,o)){let i=await n.arrayBuffer();t=us(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(yu,"getBodyResult");function bu(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(bu,"matchesContentType");function wu(n,e=!1){if(!e)return n;let t=_r(n),r=ns(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(wu,"getResourcePath");var Ru=[502,503,504];async function ct(n,e){if(Ru.includes(n.status)){let t=Y.getLogger(e),o=await n.clone().text(),i={};for(let[a,u]of n.headers)i[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:i})}}s(ct,"logBadGatewayResponses");var Ur;function je(n){if(Ur===void 0){let t=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Ur=t}return n.log[Ur]}s(je,"getHandlerUserLogFunction");async function Pu(n,e){h("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 m("Open API Spec Handler must have 'openApiFilePath' specified");let a=Iu(i);if(!a.isValid)throw new m(a.error);let u;y.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${t}${i.substring(1)}`;let c=await $.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return T.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return ct(l,e),l}s(Pu,"openApiSpecHandler");var Iu=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 Eu(n,e){h("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}s(Eu,"redirectHandler");function xu(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(xu,"join");async function Tu(n,e){h("handler.url-forward");let t=je(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,i),c=xu(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await $.fetch(l,{method:n.method,body:n.body,headers:n.headers}),g=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${g}ms`),ct(p,e),p}s(Tu,"urlForwardHandler");var vu=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 Su(n,e){h("handler.url-rewrite");let t=je(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?vu(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await $.fetch(c.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`),ct(d,e),d}s(Su,"urlRewriteHandler");async function Cu(n,e){h("handler.websocket");let t=e.route.handler.options,r=je(e);if(!t||!t.rewritePattern)throw new m("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 m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await $.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}s(Cu,"webSocketHandler");var Zr=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",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),ps=s(async(n,e,t,r,o,i)=>{let a=n.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function ms(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 u=s(async c=>{let l=await ps(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s(ms,"wireUpListeners");async function Ou(n,e){h("handler.websocket-pipeline");let t=e.route.handler.options,r=je(e);if(!t||!t.rewritePattern)throw new m("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 m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await $.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let S=await c.text(),H=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${S}'`;throw new Error(H)}let l=new WebSocketPair,[d,p]=Object.values(l),g=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${g}ms`);let f=c.webSocket;f.accept(),p.accept();let O=t.policies&&t.policies.inbound?Zr(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?Zr(t.policies.outbound,"outbound"):[];return ms(p,f,n,e,O),ms(f,p,n,e,P),new Response(null,{status:101,webSocket:d})}s(Ou,"webSocketPipelineHandler");var qr=class extends le{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Fr(this.options)}},Fr=class{static{s(this,"DynaTraceTransport")}constructor(e){h("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}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:He(we(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"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.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await $.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new J("dyna-trace-log-transport",10,this.#i)};var $r=class extends le{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Br(this.options)}},jr=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=e=>this.level===e.level&&this.requestId===e.requestId};function Au(n,e){return btoa(`${n}:${e}`)}s(Au,"createBasicDigest");var Br=class{static{s(this,"LokiTransport")}constructor(e){h("logging.loki"),this.#n=e.url,this.#r=Au(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"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new jr(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let i={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:He(we(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=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:r.atomicCounter}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);await $.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new J("loki-log-transport",10,this.#u)};var zr=class extends le{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Vr(this.options)}},Vr=class{static{s(this,"SumoLogicTransport")}constructor(e){h("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}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:He(we(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.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
51
- `),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),await $.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new J("sumo-logic-log-transport",10,this.#s)};var Lu="d3a5b78f823648f5b1df4fe269d41172",Gr=class extends le{constructor(t){super();this.options=t}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Wr(this.options)}},Wr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){h("logging.vmware-loginsight");let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??Lu}`)}catch{throw new m(`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=Vi(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 u=Pr(a);u&&o.fields.push({name:i,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let t=await $.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(t.status!==200)try{let r=await t.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new J("vmware-log-insights-log-transport",10,this.#a)};var Kr=class extends le{constructor(t){super();this.options=t}static{s(this,"AWSLoggingPlugin")}getTransport(){return new Jr(this.options)}},Jr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new J("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});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}})});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:i}){h("logging.aws"),this.awsClient=new at({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=t,this.region=i,this.environmentType=y.instance.loggingEnvironmentType,this.environment=y.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:He(we(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var Yr=new WeakMap,ku={tags:[]},Xr=class extends qe{constructor(t){super();this.options=t;h("metrics.datadog")}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new Qr(this.options)}static setContext(t,r){let o=Yr.get(t);o||(o=ku);let i=Object.assign({...o},r);Yr.set(t,i)}},Qr=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 J("data-dog-metrics-transport",10,this.dispatchFunction,Y.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Yr.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=async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),r=await $.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new eo(await r.text())}},eo=class n extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var to=new WeakMap,_u={dimensions:[]},no=class extends qe{constructor(t){super();this.options=t;h("metrics.dynatrace")}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new ro(this.options)}static setContext(t,r){let o=to.get(t);o||(o=_u);let i=Object.assign({...o},r);to.set(t,i)}},ro=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 J("dynatrace-metrics-transport",10,this.dispatchFunction,Y.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(to.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=async e=>{if(e.length===0)return;let t=e.join(`
52
- `),r=await $.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new oo(await r.text())}},oo=class n extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var io=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,h("audit-logs.datastax")}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await $.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var so=class extends De{static{s(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,h("audit-logs")}#e;#t;async initialize(e){new ao(e,this.#e,this.#t)}},gs=s(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),Nu={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},ao=class{static{s(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...Nu};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 J("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,t,r,o,i,a)=>{try{let u={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?gs(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?gs(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=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(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-i,c.user?.sub).catch(g=>{t.log.error(g)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}}};var uo=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}},Ne=class extends uo{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var Du="v1",Mu=300;async function fs(n,e,t,r=Mu,o){return await Uu(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}s(fs,"constructEventAsync");function Hu(n,e){return`${e.timestamp}.${n}`}s(Hu,"makeHMACContent");async function Uu(n,e,t,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=Zu(n,e,Du),l=/\s/.test(t),d=await ju(Hu(a,u),t);return qu(a,i,u,d,r,c,l,o)}s(Uu,"verifyHeaderAsync");function Zu(n,e,t){if(!n)throw new Ne(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 Ne(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Fu(a,t);if(!u||u.timestamp===-1)throw new Ne(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Ne(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(Zu,"parseEventDetails");function qu(n,e,t,r,o,i,a,u){let c=!!t.signatures.filter(g=>$u(g,r)).length,l=`
50
+ `)}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 _("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=qr(await cs(this.body||""))}return e}};async function Zt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Ur.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Ur.encode(e))}s(Zt,"hmac");async function cs(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Ur.encode(n):n)}s(cs,"hash");function qr(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(qr,"buf2hex");function ls(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(ls,"encodeRfc3986");function fu(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 u=(e.get("X-Amz-Target")||"").split(".")[0];u==="AnyScaleFrontendService"?i="application-autoscaling":u==="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 us?[us[i],a]:[i,a]}s(fu,"guessServiceRegion");function hu(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(hu,"b64ToUint6");function ps(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,u,c=0,l=0;for(let d=0;d<r;d++)if(u=d&3,c|=hu(t.charCodeAt(d))<<6*(3-u),u===3||r-d===1){for(a=0;a<3&&l<o;)i[l]=c>>>(16>>>a&24)&255,a++,l++;c=0}return i}s(ps,"base64Decode");function wn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(wn,"uint6ToB64");function ms(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(wn(o>>>18&63),wn(o>>>12&63),wn(o>>>6&63),wn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(ms,"base64Encode");function ut(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(ut,"numberToString");function yu(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=ut(Math.floor(t/60)),i=ut(t%60);return`${r}${o}${i}`}s(yu,"getCLFOffset");function Fr(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=ut(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),i=ut(n.getHours()),a=ut(n.getMinutes()),u=ut(n.getSeconds()),c=yu(n);return`${t}/${r}/${o}:${i}:${a}:${u} ${c}`}s(Fr,"toCLFDate");var gs=(0,fs.debug)("zuplo:runtime"),bu="X-Amzn-Trace-Id",wu="x-amzn-errortype",hs=[],Ru=s(async(n,e,t)=>{let r=t;for await(let o of hs)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),xe=class extends _{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(bu)??void 0,this.errorType=t.get(wu)??void 0}},Pu={addSendingAwsLambdaEventHook:n=>{hs.push(n)}};async function Iu(n,e){g("handler.aws-lambda");let{accessKeyId:t,secretAccessKey:r,region:o,functionName:i,useLambdaProxyIntegration:a=!0,useAwsResourcePathStyle:u=!1,binaryMediaTypes:c}=e.route.handler.options;if(!t)throw new m("awsAccessKeyId is not set in the handler options");if(!r)throw new m("secretAccessKey is not set in the handler options");if(!o)throw new m("region is not set in the handler options");if(!i)throw new m("functionName is not set in the handler options");let l=new at({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(gs(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,f]=await vu(n,{binaryMediaTypes:c}),{options:h}=e.route.handler,O;h&&typeof h=="object"&&"payloadFormatVersion"in h&&h.payloadFormatVersion==="2.0"?O=Tu(n,e):O=await xu(n,e,{useAwsResourcePathStyle:u}),gs("Calling onSendingAwsLambdaEvent hook");let P=await Ru(n,e,O);P.body=p,P.isBase64Encoded=f;let S=await l.fetch(d,{body:JSON.stringify(P)});try{return Eu(S)}catch(H){if(H instanceof xe){let k=h&&typeof h=="object"&&"returnAmazonTraceIdHeader"in h&&h.returnAmazonTraceIdHeader&&H.traceId?{AMZN_TRACE_ID_HEADER:H.traceId}:void 0;return x.internalServerError(n,e,void 0,k)}throw H}}s(Iu,"awsLambdaHandler");async function Eu(n){let e;try{e=await n.json()}catch{throw new xe("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 xe(e.message,n.headers):new xe(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new xe(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 xe(`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 xe(`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 xe(`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 xe("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new xe("Response was set to base64 encoded but body was not a string",n.headers);r=ps(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 xe(`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(Eu,"getResponse");async function xu(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]=[d];let u=new URL(n.url);return{version:"1.0",resource:u.pathname,path:u.pathname,httpMethod:n.method,headers:r,multiValueHeaders:o,queryStringParameters:i,multiValueQueryStringParameters:a,requestContext:{accountId:null,apiId:null,authorizer:{claims:{},scopes:[]},domainName:u.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:u.pathname,protocol:"HTTP/1.1",requestId:e.requestId,requestTime:Fr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:Cu(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(xu,"buildEventVersion1");function Tu(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:Fr(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(Tu,"buildEventVersion2");async function vu(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&&Su(e,o)){let i=await n.arrayBuffer();t=ms(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(vu,"getBodyResult");function Su(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(Su,"matchesContentType");function Cu(n,e=!1){if(!e)return n;let t=Hr(n),r=as(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(Cu,"getResourcePath");var Ou=[502,503,504];async function ct(n,e){if(Ou.includes(n.status)){let t=X.getLogger(e),o=await n.clone().text(),i={};for(let[a,u]of n.headers)i[a]=u;t.warn(`BadGatewayResponse ${n.status}`,{status:n.status,statusText:n.statusText,body:o,headers:i})}}s(ct,"logBadGatewayResponses");var $r;function je(n){if($r===void 0){let t=y.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),$r=t}return n.log[$r]}s(je,"getHandlerUserLogFunction");async function Au(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 m("Open API Spec Handler must have 'openApiFilePath' specified");let a=Lu(i);if(!a.isValid)throw new m(a.error);let u;y.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${t}${i.substring(1)}`;let c=await F.fetch(u,{method:n.method,body:n.body,headers:n.headers});if(c.status!==200)return x.notFound(n,e,{detail:"OpenAPI file could not be found."});let l=new Response(c.body,{headers:{"content-type":"application/json"},status:c.status,statusText:c.statusText});return ct(l,e),l}s(Au,"openApiSpecHandler");var Lu=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 ku(n,e){g("handler.redirect");let t=e.route.handler.options;if(!t.location)throw new m("Redirect Handler must have 'location' specified");let r=t.status??302;return new Response(null,{status:r,headers:{location:t.location}})}s(ku,"redirectHandler");function _u(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(_u,"join");async function Nu(n,e){g("handler.url-forward");let t=je(e),r=e.route.handler.options,o=r.forwardSearch!==!1;if(!r.baseUrl)throw new Error("URL Forward Handler must have 'baseUrl' specified");if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=new URL(n.url),u=r.__rewriteFunction(n,i),c=_u(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await F.fetch(l,{method:n.method,body:n.body,headers:n.headers}),f=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${f}ms`),ct(p,e),p}s(Nu,"urlForwardHandler");var Du=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 Mu(n,e){g("handler.url-rewrite");let t=je(e),r=e.route.handler.options,o=r.forwardSearch!==!1,i=r.followRedirects??!1;if(!r||typeof r.__rewriteFunction!="function")throw new m("Invalid options for this route");let a={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},u=r.__rewriteFunction(n,a),c=o?Du(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await F.fetch(c.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`),ct(d,e),d}s(Mu,"urlRewriteHandler");async function Hu(n,e){g("handler.websocket");let t=e.route.handler.options,r=je(e);if(!t||!t.rewritePattern)throw new m("WebSocket Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let d=await c.text(),p=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${d}'`;throw new Error(p)}let l=Date.now()-u;return r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${l}ms`),new Response(null,{status:101,webSocket:c.webSocket})}s(Hu,"webSocketHandler");var jr=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",u=`policy in position: ${o+1}, export name: ${r.export}`;throw new m(`${a} - Websocket policy must be a valid function (${u})`)}return i}),"getWebSocketPolicyFunctions"),ys=s(async(n,e,t,r,o,i)=>{let a=n.data;if(i&&i.length>0){let u=[...i];for(;u.length>0;){let c=u.shift();if(!c)return a;if(a=await c(a,t,e,r,o),a===void 0)return}}return a},"webSocketPolicyProcessor");function bs(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 u=s(async c=>{let l=await ys(c,n,e,t,r,o);l!==void 0&&e.send(l)},"innerPipeline")(i).catch(r.log.error);r.waitUntil(u)}catch(a){r.log.error(a)}})}s(bs,"wireUpListeners");async function qu(n,e){g("handler.websocket-pipeline");let t=e.route.handler.options,r=je(e);if(!t||!t.rewritePattern)throw new m("WebSocket Pipeline Handler must have option 'rewritePattern' specified");let o=n.headers.get("Upgrade");if(!o||o!=="websocket")return x.badRequest(n,e,{detail:"Request must include header 'Upgrade: websocket'"});if(!t||typeof t.__rewriteFunction!="function")throw new m("Invalid options for this route");let i={incomingRequestProperties:e.incomingRequestProperties,requestId:e.requestId,route:e.route,custom:e.custom},a=t.__rewriteFunction(n,i),u=Date.now();r(`Attempting WebSocket connection to '${a}'`),a=a.replace(/^(ws)/,"http");let c=await F.fetch(a,{method:n.method,headers:n.headers,body:n.body});if(c.status!==101||!c.webSocket){let S=await c.text(),H=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${S}'`;throw new Error(H)}let l=new WebSocketPair,[d,p]=Object.values(l),f=Date.now()-u;r(`WebSocket connected, received response ${c.status} - ${c.statusText} in ${f}ms`);let h=c.webSocket;h.accept(),p.accept();let O=t.policies&&t.policies.inbound?jr(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?jr(t.policies.outbound,"outbound"):[];return bs(p,h,n,e,O),bs(h,p,n,e,P),new Response(null,{status:101,webSocket:d})}s(qu,"webSocketPipelineHandler");var zr=class extends pe{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Br(this.options)}},Br=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}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:He(Re(r)),severity:e.level,"log.source":e.logSource,requestId:e.requestId,"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.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#i=async e=>{e.length!==0&&await F.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new J("dyna-trace-log-transport",10,this.#i)};var Vr=class extends pe{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Wr(this.options)}},Gr=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=e=>this.level===e.level&&this.requestId===e.requestId};function Uu(n,e){return btoa(`${n}:${e}`)}s(Uu,"createBasicDigest");var Wr=class{static{s(this,"LokiTransport")}constructor(e){g("logging.loki"),this.#n=e.url,this.#r=Uu(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"}#e;#t;#n;#r;#o;#i;#s;log(e,t){let r=new Gr(e.level,this.#o,this.#i,this.#s,this.#t,this.#e===1?e.requestId:void 0);e.messages.forEach(o=>{let i={stream:r,requestId:e.requestId,rayId:e.rayId,atomicCounter:e.vectorClock,message:He(Re(o)),nanoSecondEpoch:`${e.timestamp.getTime()}000000`};this.batcher.enqueue(i)}),t.waitUntil(this.batcher.waitUntilFlushed())}#a=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:r.atomicCounter}]:[r.nanoSecondEpoch,r.message])}),t};#u=async e=>{if(e.length===0)return;let t=this.#a(e);await F.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new J("loki-log-transport",10,this.#u)};var Kr=class extends pe{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Jr(this.options)}},Jr=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}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:He(Re(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.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}#s=async e=>{if(e.length===0)return;let t=e.map(o=>JSON.stringify(o)).join(`
51
+ `),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),await F.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new J("sumo-logic-log-transport",10,this.#s)};var Zu="d3a5b78f823648f5b1df4fe269d41172",Xr=class extends pe{constructor(t){super();this.options=t}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Yr(this.options)}},Yr=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??Zu}`)}catch{throw new m(`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=Xi(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 u=Tr(a);u&&o.fields.push({name:i,content:u})}),this.#i&&(o=this.#i(o)),o}#a=async e=>{if(e.length===0)return;let t=await F.fetch(this.#e,{method:"POST",body:JSON.stringify({events:e}),headers:{"content-type":"application/json; charset=utf-8"}});if(t.status!==200)try{let r=await t.text();console.error("Error logging to Log Insight",r)}catch(r){console.error(r)}};batcher=new J("vmware-log-insights-log-transport",10,this.#a)};var Qr=class extends pe{constructor(t){super();this.options=t}static{s(this,"AWSLoggingPlugin")}getTransport(){return new eo(this.options)}},eo=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new J("aws-log-transport",10,async e=>{if(e.length===0)return;let t=JSON.stringify({logGroupName:this.logGroupName,logStreamName:this.logStreamName,logEvents:e});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}})});constructor({accessKeyId:e,logStreamName:t,logGroupName:r,secretAccessKey:o,region:i}){g("logging.aws"),this.awsClient=new at({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=t,this.region=i,this.environmentType=y.instance.loggingEnvironmentType,this.environment=y.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:He(Re(r)),severity:e.level,source:e.logSource,environment:this.environment,requestId:e.requestId,environmentType:this.environmentType,rayId:e.rayId===null?void 0:e.rayId})};this.batcher.enqueue(o)}),t.waitUntil(this.batcher.waitUntilFlushed())}};var to=new WeakMap,Fu={tags:[]},no=class extends Ze{constructor(t){super();this.options=t;g("metrics.datadog")}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new ro(this.options)}static setContext(t,r){let o=to.get(t);o||(o=Fu);let i=Object.assign({...o},r);to.set(t,i)}},ro=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 J("data-dog-metrics-transport",10,this.dispatchFunction,X.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(to.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=async e=>{if(e.length===0)return;let t=JSON.stringify({series:e}),r=await F.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new oo(await r.text())}},oo=class n extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var io=new WeakMap,$u={dimensions:[]},so=class extends Ze{constructor(t){super();this.options=t;g("metrics.dynatrace")}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new ao(this.options)}static setContext(t,r){let o=io.get(t);o||(o=$u);let i=Object.assign({...o},r);io.set(t,i)}},ao=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 J("dynatrace-metrics-transport",10,this.dispatchFunction,X.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(io.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=async e=>{if(e.length===0)return;let t=e.join(`
52
+ `),r=await F.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new uo(await r.text())}},uo=class n extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var co=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e,g("audit-logs.datastax")}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await F.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var lo=class extends De{static{s(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t,g("audit-logs")}#e;#t;async initialize(e){new po(e,this.#e,this.#t)}},ws=s(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),ju={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},po=class{static{s(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...ju};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 J("audit-log",10,this.#r)}#e;#t;#n;#r=async e=>{await this.#t.writeLogBatch(e)};#o=async(e,t,r,o,i,a)=>{try{let u={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?ws(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?ws(e.headers):void 0,body:this.#e.include?.response?.body?await e.text():void 0}};this.#n.enqueue(u),r.waitUntil(this.#n.waitUntilFlushed())}catch(u){r.log.error(u)}};#i=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(u,c)=>{let l=Date.now(),d=u.clone(),p=this.#o(d,a,t,o,l-i,c.user?.sub).catch(f=>{t.log.error(f)});t.waitUntil(p)}),e}catch(r){return t.log.error(r),e}}};var mo=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}},Ne=class extends mo{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var zu="v1",Bu=300;async function Rs(n,e,t,r=Bu,o){return await Gu(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}s(Rs,"constructEventAsync");function Vu(n,e){return`${e.timestamp}.${n}`}s(Vu,"makeHMACContent");async function Gu(n,e,t,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=Wu(n,e,zu),l=/\s/.test(t),d=await Yu(Vu(a,u),t);return Ku(a,i,u,d,r,c,l,o)}s(Gu,"verifyHeaderAsync");function Wu(n,e,t){if(!n)throw new Ne(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 Ne(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Ju(a,t);if(!u||u.timestamp===-1)throw new Ne(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new Ne(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(Wu,"parseEventDetails");function Ku(n,e,t,r,o,i,a,u){let c=!!t.signatures.filter(f=>Xu(f,r)).length,l=`
53
53
  Learn more about webhook signing and explore webhook integration examples for various frameworks at https://github.com/stripe/stripe-node#webhook-signing`,d=a?`
54
54
 
55
55
  Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw i?new Ne(e,n,{message:`Webhook payload must be provided as a string or a Buffer (https://nodejs.org/api/buffer.html) instance representing the _raw_ request body.Payload was provided as a parsed JavaScript object instead.
@@ -58,8 +58,8 @@ Signature verification is impossible without access to the original signed mater
58
58
  `+d}):new Ne(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
59
59
  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.
60
60
  `+l+`
61
- `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Ne(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(qu,"validateComputedSignature");function Fu(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(Fu,"parseHeader");function $u(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($u,"secureCompare");async function ju(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 u=0;u<i.length;u++)a[u]=co[i[u]];return a.join("")}s(ju,"computeHMACSignatureAsync");var co=new Array(256);for(let n=0;n<co.length;n++)co[n]=n.toString(16).padStart(2,"0");function te(n,e,t="policy",r){let o=`${t} '${e}'`;if(!Je(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let i=s((c,l,d)=>{let p=n[c],g=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${g}' 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 m(`Value of '${g}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${g}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${g}' 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 m(`Value of '${g}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=s((c,l)=>(i(c,l,!0),{optional:a,required:u}),"optional"),u=s((c,l)=>(i(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}s(te,"optionValidator");var qt=class extends pe{static{s(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),h("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 fs(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);i=c?c[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 hs(n){return n!==null&&typeof n=="object"&&"id"in n&&Ie(n.id)&&"type"in n&&Ie(n.type)}s(hs,"isStripeWebhookEvent");var Bu={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await $.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 M(i)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await $.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 M(i)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await $.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 M(i)}return o}},yn=Bu;var lo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",ys="My API Key";async function bs({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=y.instance,c=new URL(`/v1/buckets/${n}/consumers`,lo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:ys,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),g=await p.json();if(p.status!==200){let f="Error creating API Key Consumer";throw a.log.error(f,g),new M(f)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}s(bs,"createConsumer");async function ws({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=y.instance,u=new URL(`/v1/buckets/${n}/consumers`,lo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:ys,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let g="Error creating API Key Consumer";throw i.log.error(g,p),new M(g)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}s(ws,"createConsumerInvite");async function Rs({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=y.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,lo);o.searchParams.set("with-api-key","true");let i=await Re({retryDelayMs:5,retries:2,logger:Y.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(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new M(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(Rs,"deleteConsumer");async function Ps({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:g}=y.instance;if(!ot(p))throw new K("No Zuplo JWT token set.");let f=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(n)},`${g}/internal/v1/metering/${o}/subscriptions`,{headers:{Authorization:`Bearer ${p}`,"Content-Type":"application/json","zp-rid":n.requestId},method:"POST",body:JSON.stringify(d)});if(!f.ok){let O=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,S="";try{P=await f.json(),S=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:f.status,detail:f.statusText}}throw n.log.error(O,P),new M(`${O} ${S}`)}n.log.info("Successfully created monetization subscription.",d)}s(Ps,"createSubscription");async function lt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!ot(o))throw new K("No Zuplo JWT token set.");let a=await Re({retryDelayMs:5,retries:2,logger:Y.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 u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new M(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}s(lt,"updateSubscription");async function dt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!ot(o))throw new K("No Zuplo JWT token set.");let a=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`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(c,l),new M(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new M(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new M(c)}return u.data[0]}s(dt,"getSubscription");var re="Skipping since we're unable to process the webhook event.",Be="Successfully processed the webhook event",Pe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function bn(n){return n.replaceAll("_","-")}s(bn,"stripeStatusToMeteringStatus");function et(n){return new Date(n*1e3).toISOString()}s(et,"unixTimestampToISOString");async function po(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:re,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:re,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:re,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:re,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.`+Pe});let u=i.product,c,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,c=await bs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await yn.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:re,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await ws({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,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:re,detail:p.message})}if(!c)return T.ok(n,e,{title:re,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=bn(t.data.object.status),g;l&&d&&(g={subscriber:{sub:d,email:l}});let f;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")&&(f={trialEndStatus:t.data.object.trial_settings.end_behavior.missing_payment_method,trialEndDate:et(t.data.object.trial_end),trialStartDate:et(t.data.object.trial_start)}),await Ps({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:g,trial:f})}catch(p){return await Rs({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),T.ok(n,e,{title:re,detail:p.message})}return T.ok(n,e,{title:Be})}s(po,"onCustomerSubscriptionCreated");async function mo(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:re,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:re,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:re,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.`+Pe});try{let a=await dt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await lt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return T.ok(n,e,{title:re,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. `+Pe})}return T.ok(n,e,{title:Be})}s(mo,"onCustomerSubscriptionDeleted");async function go(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:re,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:re,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:re,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.`+Pe});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 u=await dt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=bn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=et(t.data.object.trial_end)),await lt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return T.ok(n,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.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. `+Pe})}return T.ok(n,e,{title:Be})}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 u=await dt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await yn.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(g=>g.proration&&g.price.product===c),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 lt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return T.ok(n,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.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. `+Pe})}return T.ok(n,e,{title:Be})}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 u=await dt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?et(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?et(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await lt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return T.ok(n,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.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. `+Pe})}return T.ok(n,e,{title:Be})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),T.ok(n,e,{title:re,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."+Pe})}s(go,"onCustomerSubscriptionUpdated");var Is=class extends zt{constructor(t){super();this.options=t;h("monetization.stripe")}static{s(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=s(async(c,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(be.ZUPLO_METERING_SERVICE_BUCKET_ID)d=be.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(be.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=be.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new K("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let g=this.options.primaryDataRegion??"us-central1";if(!zu(g))throw new m(`StripeMonetizationPlugin - The value '${g}' on the property 'primaryDataRegion' is invalid.`);let f=await c.json();if(!hs(f))return T.ok(c,l,{title:re,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Pe});switch(l.log.info(`Received Stripe webhook event of type '${f.type}' with ID '${f.id}'.`),f.type){case"customer.subscription.created":return await po(c,l,f,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await go(c,l,f,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await mo(c,l,f,{meteringBucketId:d});default:return T.ok(c,l,{title:re,detail:`Event '${f.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.`+Pe})}},"stripeWebhookHandler"),i=Hi({inboundPolicies:[new qt({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 ce({processors:[fe,i],handler:o,gateway:r}),u=new ie({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function zu(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(zu,"isMetricsRegion");var xs=new WeakMap,Es={},fo=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){xs.set(e,t)}};async function Vu(n,e,t,r){if(h("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=it(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=xs.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new M(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ye(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){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:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},g=Es[t.apiKey];if(!g){let f=t.apiKey,O=n.headers.get("zm-test-id")??"";g=new J("amberflo-ingest-meter",10,async P=>{try{let S=t.url??"https://app.amberflo.io/ingest",H=await $.fetch(S,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":f,"zm-test-id":O}});H.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${H.status}: ${await H.text()}`)}catch(S){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${S.message}`),S}}),Es[f]=g}g.enqueue(p),e.waitUntil(g.waitUntilFlushed())}}),n}s(Vu,"AmberfloMeteringInboundPolicy");async function wn(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(wn,"sha256");var Ts=new Map;async function de(n,e,t){let r,o=`${n}-${e}`,i=Ts.get(o);return i!==void 0?r=i:(r=`zuplo-policy-${await wn(JSON.stringify({policyName:n,options:t}))}`,Ts.set(n,r)),r}s(de,"getPolicyCacheName");var vs="key-metadata-cache-type";function Gu(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(Gu,"getKeyValue");async function ho(n,e,t,r){if(h("policy.inbound.api-key"),!t.bucketName)if(be.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=be.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`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 m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(S=>o.allowUnauthenticatedRequests?n:T.unauthorized(n,e,{detail:S}),"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 u=Gu(a,o);if(!u||u==="")return i("No key present");let c=await Wu(u),l=await de(r,void 0,o),d=new ue(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==vs&&Y.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let g={key:u},f=await Re({retryDelayMs:5,retries:2,logger:Y.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":y.instance.deploymentName??"unknown","User-Agent":y.instance.systemUserAgent},body:JSON.stringify(g)});if(f.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(f.status!==200){try{let S=await f.text(),H=JSON.parse(S);e.log.error("Unexpected response from key service",H)}catch{e.log.error("Invalid response from key service")}throw new M(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${f.status}`)}let O=await f.json(),P={isValid:!0,typeId:vs,user:{sub:O.name,data:O.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}s(ho,"ApiKeyInboundPolicy");async function Wu(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(Wu,"hashValue");var Ku=ho;import{createRemoteJWKSet as Yu,jwtVerify as Cs}from"jose";import{createLocalJWKSet as Ju}from"jose";var yo=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 bo&&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=Ju(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,u=!1;typeof AbortController=="function"&&(i=new AbortController,a=setTimeout(()=>{u=!0,i.abort()},t));let c=await $.fetch(e.href,{signal:i?i.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new wo("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new pt("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new pt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function Ss(n,e,t){let r=new yo(n,e,t);return async(o,i)=>r.getKey(o,i)}s(Ss,"createRemoteJWKSet");var pt=class extends M{static{s(this,"JWKSError")}},bo=class extends pt{static{s(this,"JWKSNoMatchingKey")}},wo=class extends pt{static{s(this,"JWKSTimeout")}};var Rn={},Xu=s((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!Rn[r.jwkUrl]){let i=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(i=r.useExperimentalInMemoryCache),i){let a=await de(n,void 0,r),u=new ue(a,e);Rn[r.jwkUrl]=Ss(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else Rn[r.jwkUrl]=Yu(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await Cs(t,Rn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Qu=s(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("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 Cs(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ye=s(async(n,e,t,r)=>{h("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),i="bearer ",a=s(g=>T.unauthorized(n,e,{detail:g}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?Xu(r,e):Qu,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let g=o.substring(i.length);if(!g||g.length===0)return a("No bearer token on authorization header");try{return await u(g,t)}catch(f){let O=new URL(n.url);return"code"in f&&f.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${O.pathname} `,f):e.log.warn(`Invalid token on: ${n.method} ${O.pathname}`,f),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var ec=s(async(n,e,t,r)=>(h("policy.inbound.auth0-jwt-auth"),ye(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var Ro=class n extends pe{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),h("policy.inbound.axiomatics-authz"),te(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Ko(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(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),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(u=>u.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(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.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 tc=s(async(n,e,t)=>{h("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",i=s(l=>T.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=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 g=d.substring(0,p),f=d.substring(p+1),O=t.accounts.find(P=>P.username===g&&P.password===f);return O||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function Pn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(Pn,"extractDateElements");function Os(n,e){return new Date(n,e+1,0).getDate()}s(Os,"getDaysInMonth");function Po(n,e){return n<=e?e-n:6-n+e+1}s(Po,"getDaysBetweenWeekdays");var In=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((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(i).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=s((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).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=Os(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>i?e==="next"?void 0:i:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>i&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(g=>g>=d)??this.weekdays[0]:this.reversed.weekdays.find(g=>g<=d)??this.reversed.weekdays[0];if(p!==void 0){let g=e==="next"?Po(d,p):Po(p,d);l=e==="next"?o+g:o-g,(l>i||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=Pn(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 u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let g=this.findAllowedTime("next",t);if(g!==void 0)return new Date(u,c,d,g.hour,g.minute,g.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,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=Pn(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 u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let g=this.findAllowedTime("prev",t);if(g!==void 0)return new Date(u,c,d,g.hour,g.minute,g.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,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:u}=Pn(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(u)!==-1:this.days.indexOf(i)!==-1&&this.weekdays.indexOf(u)!==-1}};var nc={min:0,max:59},rc={min:0,max:59},oc={min:0,max:23},ic={min:1,max:31},sc={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"}},ac={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},uc={"@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 tt(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=>{tt(d,e).forEach(g=>t.add(g))}),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]),u=i[1]==="*"?e.max:o(i[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=i[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}s(tt,"parseElement");function Io(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=uc[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],u=e.length===6?e[5]:e[4];return new In({seconds:tt(t,nc),minutes:tt(r,rc),hours:tt(o,oc),days:tt(i,ic),months:new Set(Array.from(tt(a,sc)).map(c=>c-1)),weekdays:new Set(Array.from(tt(u,ac)).map(c=>c%7))})}s(Io,"parseCronExpression");var Eo=class extends pe{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),h("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 m(`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=[Io(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Io(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 cc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function lc(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(lc,"digestMessage");var dc=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 lc(JSON.stringify(r)),i=new URL(n.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function pc(n,e,t,r){h("policy.inbound.caching");let o=await de(r,t.cacheId,t),i=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await dc(n,t),c=await i.match(u);return c||(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 g=t?.expirationSecondsTtl??60,f=new Response(p.body,p);cc.forEach(O=>f.headers.delete(O)),f.headers.set("cache-control",`s-maxage=${g}`),e.waitUntil(i.put(u,f))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}s(pc,"CachingInboundPolicy");var mc=s(async(n,e,t,r)=>{if(h("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new ee(n,{method:t.method})},"ChangeMethodInboundPolicy");var gc=s(async(n,e,t)=>{h("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new ee(n,{headers:o})},"ClearHeadersInboundPolicy");var fc=s(async(n,e,t,r)=>{h("policy.outbound.clear-headers");let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&i.set(u,c)}),new Response(n.body,{headers:i,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var hc=s(async(n,e,t,r)=>{h("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",ye(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var yc=s(async(n,e,t,r)=>{if(h("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return ye(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 _s=ze(Ve());var En=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},xo=class extends En{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},To=class extends En{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function bc(n,e){if(Oi(n))throw new xo(e)}s(bc,"throwIfUndefinedOrNull");function Ft(n,e){if(bc(n,e),!Ie(n))throw new To(e,"string")}s(Ft,"throwIfNotString");var xn=class n{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return Ft(e,"redisClientUrl"),Ft(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){Ft(e,"url");let i=await $.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new K("Rate limiting service failed with 401: Unauthorized"):new K(`Rate limiting service failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Tn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(Ft(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(t),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new K("The in-memory rate limit client does not support this request")}};var wc=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 mt(n,e){return{function:Ec(e,"RateLimitInboundPolicy",n),user:Pc,ip:Rc,all:Ic}[e.rateLimitBy??"ip"]}s(mt,"getRateLimitByFunctions");var Rc=s(async n=>({key:`ip-${wc(n)}`}),"getIP"),Pc=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Ic=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),vn;function gt(n,e){let t;if(vn)return vn;if(!y.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),t=new Tn,vn=t,t;let{authApiJWT:r,redisURL:o}=y.instance;if(!Ie(o))throw new K(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Ie(r))throw new K(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=xn.initialize(o,r,y.instance.deploymentName??"unknown",y.instance.systemUserAgent)),!t||!t.isEnabled())throw new K(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return vn=t,t}s(gt,"getRedisClient");async function Sn(n,e,t,r){let o=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:n}),requestId:r})}s(Sn,"getCountAndUpdateExpiry");async function As(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}s(As,"multiCount");async function Ls(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}s(Ls,"multiIncrement");function Ec(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${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 m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,a,u)=>{let c=await r(i,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new M(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new M(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new M(l)}return c},"outerFunction")}s(Ec,"wrapUserFunction");var ft="Retry-After";var ks=(0,_s.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),vo=Symbol("complex-rate-limit-counters"),So=class n extends pe{static{s(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=he.get(e,vo)??{};Object.assign(r,t),he.set(e,vo,t)}static getIncrements(e){return he.get(e,vo)??{}}constructor(e,t){super(e,t),h("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 m(`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=Y.getLogger(t),i=gt(this.policyName,o),a=s((c,l)=>{if(this.options.throwOnFailure)throw new K(c,{cause:l});o.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[ft]=l.toString()),T.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await mt(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),g=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let S=n.getIncrements(t);ks(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(S)}`);let H=Object.entries(p).map(([j])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${j}`,ttlSeconds:g,increment:S[j]??0})),k=Ls(H,i,t.requestId);t.waitUntil(k),await k}catch(S){t.log.error(S)}});let f=Object.entries(p).map(([S,H])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${S}`,ttlSeconds:g,limit:H})),O=await As(f,i,t.requestId);return xc(O,f).length>0?u(this.options.headerMode??"retry-after",g):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;ks(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function xc(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(xc,"findOverLimits");var Tc=s(async(n,e,t,r)=>{if(h("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=me.instance,i=At(t.policies,o?.routeData.policies);return br(i)(n,e)},"CompositeInboundPolicy");var vc=s(async(n,e,t,r)=>{h("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=Sc(o);if(!i)return T.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await de(r,void 0,t),u=new ue(a,e),c=await u.get(i);if(!c){let l=await $.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)c=d,u.put(i,c,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 ${c}`),n},"CurityPhantomTokenInboundPolicy");function Sc(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(Sc,"getToken");var Cc=s(async(n,e,t,r)=>(h("policy.inbound.firebase-jwt-auth"),te(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ye(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 Oc=s(async(n,e,t)=>{h("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 u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new ee(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ht="__unknown__",Ac=s(async(n,e,t,r)=>{h("policy.inbound.geo-filter");let o={allow:{countries:bt(t.allow?.countries,"allow.countries",r),regionCodes:bt(t.allow?.regionCodes,"allow.regionCode",r),asns:bt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:bt(t.block?.countries,"block.countries",r),regionCodes:bt(t.block?.regionCodes,"block.regionCode",r),asns:bt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??ht,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ht,u=e.incomingRequestProperties.asn?.toString()??ht,c=o.ignoreUnknown&&i===ht,l=o.ignoreUnknown&&a===ht,d=o.ignoreUnknown&&u===ht,p=o.allow.countries,g=o.allow.regionCodes,f=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||g.length>0&&!g.includes(a)&&!l||f.length>0&&!f.includes(u)&&!d)return yt(n,e,r,i,a,u);let O=o.block.countries,P=o.block.regionCodes,S=o.block.asns;return O.length>0&&O.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||S.length>0&&S.includes(u)&&!d?yt(n,e,r,i,a,u):n},"GeoFilterInboundPolicy");function yt(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(yt,"blockedResponse");function bt(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 m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}s(bt,"toLowerStringArray");var Lc=s(async(n,e,t)=>{h("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"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 kc=s(async(n,e,t,r)=>{h("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return Co(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 Co(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(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(g=>{a.push({responseName:u,contentName:l,exampleName:g,exampleValue:d[g]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Ns(a[u])}else return a.length>0?Ns(a[0]):Co(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 Ns(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(Ns,"generateResponse");var Co=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 _c="Incoming",Nc={logRequestBody:!0,logResponseBody:!0};function Ds(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(Ds,"headersToObject");function Ms(){return new Date().toISOString()}s(Ms,"timestamp");var Oo=new WeakMap,Dc={};function Mc(n,e){let t=Oo.get(n);t||(t=Dc);let r=Object.assign({...t},e);Oo.set(n,r)}s(Mc,"setMoesifContext");async function Hs(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(Hs,"readBody");var Hc={},Ao;function Us(){if(!Ao)throw new M("Invalid State - no _lastLogger");return Ao}s(Us,"getLastLogger");function Uc(n){let e=Hc[n];return e||(e=new J("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Us().debug("posting",r);let o=await $.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||Us().error({status:o.status,body:await o.text()})})),e}s(Uc,"getDispatcher");async function Zc(n,e,t,r){h("policy.inbound.moesif-analytics"),Ao=e.log;let o=Ms(),i=Object.assign(Nc,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Hs(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Uc(i.applicationId),d=n.headers.get("true-client-ip"),p=Oo.get(e)??{},g={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Ds(n.headers)},f=i.logResponseBody?await Hs(u,e):void 0,O={time:Ms(),status:u.status,headers:Ds(u.headers),body:f},P={request:g,response:O,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:_c};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}s(Zc,"MoesifInboundPolicy");async function Zs(n,e,t,r){let o=Y.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=y.instance,u;try{let l=await $.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=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 c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}s(Zs,"loadSubscription");async function qs(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=y.instance,u=Y.getLogger(n);try{let c=await $.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(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}s(qs,"consumeSubcriptionQuotas");var qc=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Cn(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 m(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 m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}s(Cn,"validateMeters");function Fs(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=Xe(n),r=[];for(let o of t)qc.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}s(Fs,"parseAllowedSubscriptionStatuses");function $s(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($s,"compareMeters");var Lo=class extends pe{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return he.get(e,It)}static setMeters(e,t){Cn(t,"setMeters"),he.set(e,jt,t)}constructor(e,t){super(e,t),h("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=it(this.options.meterOnStatusCodes),i=he.get(t,jt),a={...this.options.meters,...i};Cn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Fs(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,S,H)=>{let k=he.get(H,It);if((this.options.allowRequestsWithoutSubscription??!1)&&!k){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(be.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=be.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let Z=he.get(H,jt),F={...this.options.meters,...Z};if(Cn(F,this.policyName),o.includes(P.status)&&k&&F){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${k.id}' with meters '${JSON.stringify(F)} on response status '${P.status}'`);let{metersInSubscription:E,metersNotInSubscription:D}=$s(k.meters,F);if(D&&Object.keys(D).length>0){let V=Object.keys(D);H.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await qs(H,k.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return u?e:T.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(be.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=be.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Zs(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:T.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)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"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),he.set(t,It,p));let g=he.get(t,It);if(!g)return u?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(g&&Object.keys(g.meters).length===0)return t.log.error(`Quota is not set up for subscription '${g.id}'`),T.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let O=Object.keys(a).filter(P=>!Object.keys(g.meters).includes(P));if(O.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${O.join(", ")}`),T.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${O.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(g.meters[P].available<=0&&!r)return T.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};var Fc=s(async(n,e,t,r)=>(h("policy.inbound.okta-jwt-auth"),ye(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");import{importSPKI as $c}from"jose";var ko,jc=s(async(n,e,t,r)=>{if(h("policy.inbound.propel-auth-jwt-auth"),!ko)try{ko=await $c(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ye(n,e,{issuer:t.authUrl,secret:ko,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Gs=ze(Ve());var Bs=ze(Ve());var js=(0,Bs.debug)("zuplo:policies:RateLimitInboundPolicy"),zs=s(async(n,e,t,r)=>{let o=Y.getLogger(e),i=s((F,E)=>{let D={};return(!F||F==="retry-after")&&(D[ft]=E.toString()),T.tooManyRequests(n,e,void 0,D)},"rateLimited"),u=await mt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",g=gt(r,o),O=`rate-limit${y.instance.isTestMode?y.instance.build.BUILD_ID:""}/${r}/${c}`,P=await de(r,void 0,t),S=new ue(P,e),H=Sn(O,d,g,e.requestId),k;s(async()=>{let F=await H;if(F.count>l){let E=Date.now()+F.ttlSeconds*1e3;S.put(O,E,F.ttlSeconds),js(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${O}' (async mode)`),k=i(p,F.ttlSeconds)}},"asyncCheck")();let Z=await S.get(O);if(Z!==void 0&&Z>Date.now()){js(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${O}' (async mode)`);let F=Math.round((Z-Date.now())/1e3);return i(p,F)}return e.addResponseSendingHook(async F=>k??F),n},"AsyncRateLimitInboundPolicy");var Vs=(0,Gs.debug)("zuplo:policies:RateLimitInboundPolicy"),Bc="strict",Ws=s(async(n,e,t,r)=>{if(h("policy.inbound.rate-limit"),(t.mode??Bc)==="async")return zs(n,e,t,r);let i=Date.now(),a=Y.getLogger(e),u=s((l,d)=>{if(t.throwOnFailure)throw new K(l,{cause:d});a.error(l,d)},"throwOrLog"),c=s((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[ft]=d.toString()),T.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await mt(r,t)(n,e,r),p=d.key,g=d.requestsAllowed??t.requestsAllowed,f=d.timeWindowMinutes??t.timeWindowMinutes,O=t.headerMode??"retry-after",P=gt(r,a),H=`rate-limit${y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:""}/${r}/${p}`,k=await Sn(H,f,P,e.requestId);return k.count>g?(Vs(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${H}' (strict mode)`),c(O,k.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-i;Vs(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var _o;function Ks(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(Ks,"headersToNameValuePairs");function zc(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(zc,"queryToNameValueParis");function Vc(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(Vc,"parseIntOrUndefined");var Js={};async function Gc(n,e,t,r){h("policy.inbound.readme-metrics");let o=new Date,i=Date.now();return _o||(_o={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?Ye(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?Ye(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:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:_o,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:Ks(n.headers),queryString:zc(n.query)},response:{status:a.status,statusText:a.statusText,headers:Ks(a.headers),content:{size:Vc(n.headers.get("content-length"))}}}]}}},d=Js[t.apiKey];if(!d){let p=t.apiKey;d=new J("readme-metering-inbound-policy",10,async g=>{try{let f=t.url??"https://metrics.readme.io/request",O=await $.fetch(f,{method:"POST",body:JSON.stringify(g),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});O.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${O.status}: '${await O.text()}'`)}catch(f){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${f.message}'`),f}}),Js[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}s(Gc,"ReadmeMetricsInboundPolicy");var Wc=s(async(n,e,t,r)=>{h("policy.inbound.remove-headers");let o=t?.headers;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(n.headers);return o.forEach(u=>{i.delete(u)}),new ee(n,{headers:i})},"RemoveHeadersInboundPolicy");var Kc=s(async(n,e,t,r,o)=>{h("policy.outbound.remove-headers");let i=r?.headers;if(!i||!Array.isArray(i)||i.length===0)throw new m(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return i.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var Jc=s(async(n,e,t,r)=>{h("policy.inbound.remove-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length===0)throw new m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(n.url);return o.forEach(u=>{i.searchParams.delete(u)}),new ee(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var Yc=s(async(n,e,t,r)=>{h("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 Ys=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Xc=s(async(n,e,t)=>{h("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?Ys():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Ys():n},"RequestSizeLimitInboundPolicy");var wt=s(n=>{let e=n.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Rt=s((n,e,t,r,o)=>{let i=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=_n(t,r,o,c.name),p=me.instance.schemaValidator[d],g=p(e[c.name]),f=No(p.errors);g||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${f.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Ce=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),Oe=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ae=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),No=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 Xs(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(f){let O=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=T.badRequest(e,n,{detail:`${O}, see errors property for more details`,errors:`${f}`});if(Oe(t.validateBody)&&Ce(n,t.logLevel??"info",O,[r],f),Ae(t.validateBody))return P}if(!e.headers.get("Content-Type")){let f=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,O=T.badRequest(e,n,{detail:f});return Oe(t.validateBody)&&Ce(n,t.logLevel??"info",f,[r],[f]),Ae(t.validateBody)?O:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Nn(n.route.path,e.method,o),u=me.instance.schemaValidator[a];if(!u){let f=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,O=T.badRequest(e,n,{detail:f});return Oe(t.validateBody)&&Ce(n,t.logLevel??"info",f,[r],[f]),Ae(t.validateBody)?O:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=No(l),g=T.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Oe(t.validateBody)&&Ce(n,t.logLevel??"info",d,[r],p),Ae(t.validateBody))return g}s(Xs,"handleBodyValidation");function Qs(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=wt(n),i=Rt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=T.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Oe(t.validateHeaders)&&Ce(n,t.logLevel??"info",a,i.invalidValues,i.errors),Ae(t.validateHeaders))return u}}s(Qs,"handleHeadersValidation");function ea(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=wt(n),o=Rt(r.filter(i=>i.location==="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(Oe(t.validatePathParameters)&&Ce(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ae(t.validatePathParameters))return a}}s(ea,"handlePathParameterValidation");function ta(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=wt(n),o=Rt(r.filter(i=>i.location==="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(Oe(t.validateQueryParameters)&&Ce(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ae(t.validateQueryParameters))return a}}s(ta,"handleQueryParameterValidation");var na=s(async(n,e,t)=>{h("policy.inbound.request-validation");let r=ta(e,n,t);if(r!==void 0||(r=ea(e,n,t),r!==void 0)||(r=Qs(e,n,t),r!==void 0))return r;let o=await Xs(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Qc=na;var el=s(async(n,e,t,r)=>{if(h("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`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 tl=s(async(n,e,t)=>(h("policy.inbound.set-body"),new ee(n,{body:t.body})),"SetBodyInboundPolicy");var nl=s(async(n,e,t,r)=>{h("policy.inbound.set-headers");let o=t.headers;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new ee(n,{headers:i})},"SetHeadersInboundPolicy");var rl=s(async(n,e,t,r,o)=>{h("policy.outbound.set-headers");let i=r.headers;if(!i||!Array.isArray(i)||i.length==0)throw new m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var ol=s(async(n,e,t,r)=>{h("policy.inbound.set-query-params");let o=t.params;if(!o||!Array.isArray(o)||o.length==0)throw new m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new ee(i.toString(),n)},"SetQueryParamsInboundPolicy");var il=s(async(n,e,t,r,o)=>{if(h("policy.outbound.set-status"),!r.status||isNaN(r.status)||r.status<100||r.status>599)throw new Error(`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 sl=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),al=s(async(n,e,t,r)=>{if(h("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await sl(t.sleepInMs),n},"SleepInboundPolicy");var ul=s(async(n,e,t,r)=>{h("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 ye(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof ee))throw new K("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return i;let u=n.user?.data.app_metadata;if(!u)throw new M(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?T.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var cl=s(async(n,e,t,r)=>{h("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 de(r,void 0,t),i=new ue(o,e),a=await i.get(r);if(!a){let u=await ll(t,e);i.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function ll(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await Re({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 M("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 M("Response returned from Azure AD is not in the expected format.")}s(ll,"getAccessToken");var ra="https://accounts.google.com/o/oauth2/token",Do,dl=s(async(n,e,t,r)=>{h("policy.inbound.upstream-firebase-admin-auth"),te(t,r).required("serviceAccountJson","string"),Do||(Do=await Ee.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 de(r,void 0,t),a=new ue(i,e),u=await a.get(r);if(!u){let c=await ke({serviceAccount:Do,audience:ra,payload:o}),l=await on(ra,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new M("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var pl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",ml=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Mo,gl=s(async(n,e,t,r)=>{if(h("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 m(`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(ml.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Mo||(Mo=await Ee.init(t.serviceAccountJson));let i=t.userId;if(!i&&!t.userIdPropertyPath){if(!n.user)throw new M("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 M(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Ye(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new M(`Unable to determine user from for the policy ${r}`);let a=await de(r,void 0,t),u=new ue(a,e),c={uid:i,claims:o},l=await wn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ke({serviceAccount:Mo,audience:pl,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,f=await Gi(g,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!f.idToken)throw new M("Invalid token response from Firebase");d=f.idToken,u.put(l,d,(f.expiresIn?parseInt(f.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var Ho,fl=s(async(n,e,t,r)=>{h("policy.inbound.upstream-gcp-jwt"),te(t,r).required("audience","string").required("serviceAccountJson","string"),Ho||(Ho=await Ee.init(t.serviceAccountJson));let o=await ke({serviceAccount:Ho,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var oa="https://www.googleapis.com/oauth2/v4/token",Uo,hl=s(async(n,e,t,r)=>{h("policy.inbound.upstream-gcp-service-auth"),te(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Uo||(Uo=await Ee.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=Xe(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let i=await de(r,void 0,t),a;t.useMemoryCacheOnly?a=new nt(i):a=new ue(i,e);let u=await a.get(r);if(!u){let c=await ke({serviceAccount:Uo,audience:oa,payload:o}),l=await on(oa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new M("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new M("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var yl=s(async(n,e,t)=>{h("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(o))return n;let{errors:a}=t.validator;if(!a)throw new K("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return T.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ia=s(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=s((P,S)=>e(P,"name",{value:S,configurable:!0}),"__name"),o=s((P,S)=>s(function(){return S||(0,P[t(P)[0]])((S={exports:{}}).exports,S),S.exports},"__require"),"__commonJS"),i=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var S={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:function(k,j){return j},attributeValueProcessor:function(k,j){return j},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(k,j,Z){return k}},H=r(function(k){return Object.assign({},S,k)},"buildOptions");P.buildOptions=H,P.defaultOptions=S}}),a=o({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var S=":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",H=S+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",k="["+S+"]["+H+"]*",j=new RegExp("^"+k+"$"),Z=r(function(E,D){let V=[],G=D.exec(E);for(;G;){let v=[];v.startIndex=D.lastIndex-G[0].length;let x=G.length;for(let U=0;U<x;U++)v.push(G[U]);V.push(v),G=D.exec(E)}return V},"getAllMatches"),F=r(function(E){let D=j.exec(E);return!(D===null||typeof D>"u")},"isName");P.isExist=function(E){return typeof E<"u"},P.isEmptyObject=function(E){return Object.keys(E).length===0},P.merge=function(E,D,V){if(D){let G=Object.keys(D),v=G.length;for(let x=0;x<v;x++)V==="strict"?E[G[x]]=[D[G[x]]]:E[G[x]]=D[G[x]]}},P.getValue=function(E){return P.isExist(E)?E:""},P.isName=F,P.getAllMatches=Z,P.nameRegexp=k}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,S){"use strict";var H=class{static{s(this,"XmlNode")}static{r(this,"XmlNode")}constructor(k){this.tagname=k,this.child=[],this[":@"]={}}add(k,j){k==="__proto__"&&(k="#__proto__"),this.child.push({[k]:j})}addChild(k){k.tagname==="__proto__"&&(k.tagname="#__proto__"),k[":@"]&&Object.keys(k[":@"]).length>0?this.child.push({[k.tagname]:k.child,":@":k[":@"]}):this.child.push({[k.tagname]:k.child})}};S.exports=H}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,S){var H=a();function k(v,x){let U={};if(v[x+3]==="O"&&v[x+4]==="C"&&v[x+5]==="T"&&v[x+6]==="Y"&&v[x+7]==="P"&&v[x+8]==="E"){x=x+9;let se=1,W=!1,X=!1,Te="";for(;x<v.length;x++)if(v[x]==="<"&&!X){if(W&&F(v,x))x+=7,[entityName,val,x]=j(v,x+1),val.indexOf("&")===-1&&(U[G(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(W&&E(v,x))x+=8;else if(W&&D(v,x))x+=8;else if(W&&V(v,x))x+=9;else if(Z)X=!0;else throw new Error("Invalid DOCTYPE");se++,Te=""}else if(v[x]===">"){if(X?v[x-1]==="-"&&v[x-2]==="-"&&(X=!1,se--):se--,se===0)break}else v[x]==="["?W=!0:Te+=v[x];if(se!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:U,i:x}}s(k,"readDocType"),r(k,"readDocType");function j(v,x){let U="";for(;x<v.length&&v[x]!=="'"&&v[x]!=='"';x++)U+=v[x];if(U=U.trim(),U.indexOf(" ")!==-1)throw new Error("External entites are not supported");let se=v[x++],W="";for(;x<v.length&&v[x]!==se;x++)W+=v[x];return[U,W,x]}s(j,"readEntityExp"),r(j,"readEntityExp");function Z(v,x){return v[x+1]==="!"&&v[x+2]==="-"&&v[x+3]==="-"}s(Z,"isComment"),r(Z,"isComment");function F(v,x){return v[x+1]==="!"&&v[x+2]==="E"&&v[x+3]==="N"&&v[x+4]==="T"&&v[x+5]==="I"&&v[x+6]==="T"&&v[x+7]==="Y"}s(F,"isEntity"),r(F,"isEntity");function E(v,x){return v[x+1]==="!"&&v[x+2]==="E"&&v[x+3]==="L"&&v[x+4]==="E"&&v[x+5]==="M"&&v[x+6]==="E"&&v[x+7]==="N"&&v[x+8]==="T"}s(E,"isElement"),r(E,"isElement");function D(v,x){return v[x+1]==="!"&&v[x+2]==="A"&&v[x+3]==="T"&&v[x+4]==="T"&&v[x+5]==="L"&&v[x+6]==="I"&&v[x+7]==="S"&&v[x+8]==="T"}s(D,"isAttlist"),r(D,"isAttlist");function V(v,x){return v[x+1]==="!"&&v[x+2]==="N"&&v[x+3]==="O"&&v[x+4]==="T"&&v[x+5]==="A"&&v[x+6]==="T"&&v[x+7]==="I"&&v[x+8]==="O"&&v[x+9]==="N"}s(V,"isNotation"),r(V,"isNotation");function G(v){if(H.isName(v))return v;throw new Error(`Invalid entity name ${v}`)}s(G,"validateEntityName"),r(G,"validateEntityName"),S.exports=k}}),l=o({"../../node_modules/strnum/strnum.js"(P,S){var H=/^[-+]?0x[a-fA-F0-9]+$/,k=/^([\-\+])?(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 j={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Z(E,D={}){if(D=Object.assign({},j,D),!E||typeof E!="string")return E;let V=E.trim();if(D.skipLike!==void 0&&D.skipLike.test(V))return E;if(D.hex&&H.test(V))return Number.parseInt(V,16);{let G=k.exec(V);if(G){let v=G[1],x=G[2],U=F(G[3]),se=G[4]||G[6];if(!D.leadingZeros&&x.length>0&&v&&V[2]!==".")return E;if(!D.leadingZeros&&x.length>0&&!v&&V[1]!==".")return E;{let W=Number(V),X=""+W;return X.search(/[eE]/)!==-1||se?D.eNotation?W:E:V.indexOf(".")!==-1?X==="0"&&U===""||X===U||v&&X==="-"+U?W:E:x?U===X||v+U===X?W:E:V===X||V===v+X?W:E}}else return E}}s(Z,"toNumber"),r(Z,"toNumber");function F(E){return E&&E.indexOf(".")!==-1&&(E=E.replace(/0+$/,""),E==="."?E="0":E[0]==="."?E="0"+E:E[E.length-1]==="."&&(E=E.substr(0,E.length-1))),E}s(F,"trimZeros"),r(F,"trimZeros"),S.exports=Z}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,S){"use strict";var H=a(),k=u(),j=c(),Z=l(),F=class{static{s(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(R){this.options=R,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:(I,A)=>String.fromCharCode(Number.parseInt(A,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(I,A)=>String.fromCharCode(Number.parseInt(A,16))}},this.addExternalEntities=E,this.parseXml=x,this.parseTextData=D,this.resolveNameSpace=V,this.buildAttributesMap=v,this.isItStopNode=X,this.replaceEntitiesValue=se,this.readStopNodeData=z,this.saveTextToParentTag=W,this.addChild=U}};function E(R){let I=Object.keys(R);for(let A=0;A<I.length;A++){let B=I[A];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:R[B]}}}s(E,"addExternalEntities"),r(E,"addExternalEntities");function D(R,I,A,B,L,_,Q){if(R!==void 0&&(this.options.trimValues&&!B&&(R=R.trim()),R.length>0)){Q||(R=this.replaceEntitiesValue(R));let q=this.options.tagValueProcessor(I,R,A,L,_);return q==null?R:typeof q!=typeof R||q!==R?q:this.options.trimValues?ae(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?ae(R,this.options.parseTagValue,this.options.numberParseOptions):R}}s(D,"parseTextData"),r(D,"parseTextData");function V(R){if(this.options.removeNSPrefix){let I=R.split(":"),A=R.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(R=A+I[1])}return R}s(V,"resolveNameSpace"),r(V,"resolveNameSpace");var G=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function v(R,I,A){if(!this.options.ignoreAttributes&&typeof R=="string"){let B=H.getAllMatches(R,G),L=B.length,_={};for(let Q=0;Q<L;Q++){let q=this.resolveNameSpace(B[Q][1]),N=B[Q][4],oe=this.options.attributeNamePrefix+q;if(q.length)if(this.options.transformAttributeName&&(oe=this.options.transformAttributeName(oe)),oe==="__proto__"&&(oe="#__proto__"),N!==void 0){this.options.trimValues&&(N=N.trim()),N=this.replaceEntitiesValue(N);let ne=this.options.attributeValueProcessor(q,N,I);ne==null?_[oe]=N:typeof ne!=typeof N||ne!==N?_[oe]=ne:_[oe]=ae(N,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(_[oe]=!0)}if(!Object.keys(_).length)return;if(this.options.attributesGroupName){let Q={};return Q[this.options.attributesGroupName]=_,Q}return _}}s(v,"buildAttributesMap"),r(v,"buildAttributesMap");var x=r(function(R){R=R.replace(/\r\n?/g,`
62
- `);let I=new k("!xml"),A=I,B="",L="";for(let _=0;_<R.length;_++)if(R[_]==="<")if(R[_+1]==="/"){let q=b(R,">",_,"Closing Tag is not closed."),N=R.substring(_+2,q).trim();if(this.options.removeNSPrefix){let Se=N.indexOf(":");Se!==-1&&(N=N.substr(Se+1))}this.options.transformTagName&&(N=this.options.transformTagName(N)),A&&(B=this.saveTextToParentTag(B,A,L));let oe=L.substring(L.lastIndexOf(".")+1);if(N&&this.options.unpairedTags.indexOf(N)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${N}>`);let ne=0;oe&&this.options.unpairedTags.indexOf(oe)!==-1?(ne=L.lastIndexOf(".",L.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ne=L.lastIndexOf("."),L=L.substring(0,ne),A=this.tagsNodeStack.pop(),B="",_=q}else if(R[_+1]==="?"){let q=C(R,_,!1,"?>");if(!q)throw new Error("Pi Tag is not closed.");if(B=this.saveTextToParentTag(B,A,L),!(this.options.ignoreDeclaration&&q.tagName==="?xml"||this.options.ignorePiTags)){let N=new k(q.tagName);N.add(this.options.textNodeName,""),q.tagName!==q.tagExp&&q.attrExpPresent&&(N[":@"]=this.buildAttributesMap(q.tagExp,L,q.tagName)),this.addChild(A,N,L)}_=q.closeIndex+1}else if(R.substr(_+1,3)==="!--"){let q=b(R,"-->",_+4,"Comment is not closed.");if(this.options.commentPropName){let N=R.substring(_+4,q-2);B=this.saveTextToParentTag(B,A,L),A.add(this.options.commentPropName,[{[this.options.textNodeName]:N}])}_=q}else if(R.substr(_+1,2)==="!D"){let q=j(R,_);this.docTypeEntities=q.entities,_=q.i}else if(R.substr(_+1,2)==="!["){let q=b(R,"]]>",_,"CDATA is not closed.")-2,N=R.substring(_+9,q);B=this.saveTextToParentTag(B,A,L);let oe=this.parseTextData(N,A.tagname,L,!0,!1,!0,!0);oe==null&&(oe=""),this.options.cdataPropName?A.add(this.options.cdataPropName,[{[this.options.textNodeName]:N}]):A.add(this.options.textNodeName,oe),_=q+2}else{let q=C(R,_,this.options.removeNSPrefix),N=q.tagName,oe=q.rawTagName,ne=q.tagExp,Se=q.attrExpPresent,Vo=q.closeIndex;this.options.transformTagName&&(N=this.options.transformTagName(N)),A&&B&&A.tagname!=="!xml"&&(B=this.saveTextToParentTag(B,A,L,!1));let Go=A;if(Go&&this.options.unpairedTags.indexOf(Go.tagname)!==-1&&(A=this.tagsNodeStack.pop(),L=L.substring(0,L.lastIndexOf("."))),N!==I.tagname&&(L+=L?"."+N:N),this.isItStopNode(this.options.stopNodes,L,N)){let ve="";if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1)_=q.closeIndex;else if(this.options.unpairedTags.indexOf(N)!==-1)_=q.closeIndex;else{let kn=this.readStopNodeData(R,oe,Vo+1);if(!kn)throw new Error(`Unexpected end of ${oe}`);_=kn.i,ve=kn.tagContent}let Ln=new k(N);N!==ne&&Se&&(Ln[":@"]=this.buildAttributesMap(ne,L,N)),ve&&(ve=this.parseTextData(ve,N,L,!0,Se,!0,!0)),L=L.substr(0,L.lastIndexOf(".")),Ln.add(this.options.textNodeName,ve),this.addChild(A,Ln,L)}else{if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1){N[N.length-1]==="/"?(N=N.substr(0,N.length-1),L=L.substr(0,L.length-1),ne=N):ne=ne.substr(0,ne.length-1),this.options.transformTagName&&(N=this.options.transformTagName(N));let ve=new k(N);N!==ne&&Se&&(ve[":@"]=this.buildAttributesMap(ne,L,N)),this.addChild(A,ve,L),L=L.substr(0,L.lastIndexOf("."))}else{let ve=new k(N);this.tagsNodeStack.push(A),N!==ne&&Se&&(ve[":@"]=this.buildAttributesMap(ne,L,N)),this.addChild(A,ve,L),A=ve}B="",_=Vo}}else B+=R[_];return I.child},"parseXml");function U(R,I,A){let B=this.options.updateTag(I.tagname,A,I[":@"]);B===!1||(typeof B=="string"&&(I.tagname=B),R.addChild(I))}s(U,"addChild"),r(U,"addChild");var se=r(function(R){if(this.options.processEntities){for(let I in this.docTypeEntities){let A=this.docTypeEntities[I];R=R.replace(A.regx,A.val)}for(let I in this.lastEntities){let A=this.lastEntities[I];R=R.replace(A.regex,A.val)}if(this.options.htmlEntities)for(let I in this.htmlEntities){let A=this.htmlEntities[I];R=R.replace(A.regex,A.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function W(R,I,A,B){return R&&(B===void 0&&(B=Object.keys(I.child).length===0),R=this.parseTextData(R,I.tagname,A,!1,I[":@"]?Object.keys(I[":@"]).length!==0:!1,B),R!==void 0&&R!==""&&I.add(this.options.textNodeName,R),R=""),R}s(W,"saveTextToParentTag"),r(W,"saveTextToParentTag");function X(R,I,A){let B="*."+A;for(let L in R){let _=R[L];if(B===_||I===_)return!0}return!1}s(X,"isItStopNode"),r(X,"isItStopNode");function Te(R,I,A=">"){let B,L="";for(let _=I;_<R.length;_++){let Q=R[_];if(B)Q===B&&(B="");else if(Q==='"'||Q==="'")B=Q;else if(Q===A[0])if(A[1]){if(R[_+1]===A[1])return{data:L,index:_}}else return{data:L,index:_};else Q===" "&&(Q=" ");L+=Q}}s(Te,"tagExpWithClosingIndex"),r(Te,"tagExpWithClosingIndex");function b(R,I,A,B){let L=R.indexOf(I,A);if(L===-1)throw new Error(B);return L+I.length-1}s(b,"findClosingIndex"),r(b,"findClosingIndex");function C(R,I,A,B=">"){let L=Te(R,I+1,B);if(!L)return;let _=L.data,Q=L.index,q=_.search(/\s/),N=_,oe=!0;q!==-1&&(N=_.substring(0,q),_=_.substring(q+1).trimStart());let ne=N;if(A){let Se=N.indexOf(":");Se!==-1&&(N=N.substr(Se+1),oe=N!==L.data.substr(Se+1))}return{tagName:N,tagExp:_,closeIndex:Q,attrExpPresent:oe,rawTagName:ne}}s(C,"readTagExp"),r(C,"readTagExp");function z(R,I,A){let B=A,L=1;for(;A<R.length;A++)if(R[A]==="<")if(R[A+1]==="/"){let _=b(R,">",A,`${I} is not closed`);if(R.substring(A+2,_).trim()===I&&(L--,L===0))return{tagContent:R.substring(B,A),i:_};A=_}else if(R[A+1]==="?")A=b(R,"?>",A+1,"StopNode is not closed.");else if(R.substr(A+1,3)==="!--")A=b(R,"-->",A+3,"StopNode is not closed.");else if(R.substr(A+1,2)==="![")A=b(R,"]]>",A,"StopNode is not closed.")-2;else{let _=C(R,A,">");_&&((_&&_.tagName)===I&&_.tagExp[_.tagExp.length-1]!=="/"&&L++,A=_.closeIndex)}}s(z,"readStopNodeData"),r(z,"readStopNodeData");function ae(R,I,A){if(I&&typeof R=="string"){let B=R.trim();return B==="true"?!0:B==="false"?!1:Z(R,A)}else return H.isExist(R)?R:""}s(ae,"parseValue"),r(ae,"parseValue"),S.exports=F}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function S(F,E){return H(F,E)}s(S,"prettify"),r(S,"prettify");function H(F,E,D){let V,G={};for(let v=0;v<F.length;v++){let x=F[v],U=k(x),se="";if(D===void 0?se=U:se=D+"."+U,U===E.textNodeName)V===void 0?V=x[U]:V+=""+x[U];else{if(U===void 0)continue;if(x[U]){let W=H(x[U],E,se),X=Z(W,E);x[":@"]?j(W,x[":@"],se,E):Object.keys(W).length===1&&W[E.textNodeName]!==void 0&&!E.alwaysCreateTextNode?W=W[E.textNodeName]:Object.keys(W).length===0&&(E.alwaysCreateTextNode?W[E.textNodeName]="":W=""),G[U]!==void 0&&G.hasOwnProperty(U)?(Array.isArray(G[U])||(G[U]=[G[U]]),G[U].push(W)):E.isArray(U,se,X)?G[U]=[W]:G[U]=W}}}return typeof V=="string"?V.length>0&&(G[E.textNodeName]=V):V!==void 0&&(G[E.textNodeName]=V),G}s(H,"compress"),r(H,"compress");function k(F){let E=Object.keys(F);for(let D=0;D<E.length;D++){let V=E[D];if(V!==":@")return V}}s(k,"propName"),r(k,"propName");function j(F,E,D,V){if(E){let G=Object.keys(E),v=G.length;for(let x=0;x<v;x++){let U=G[x];V.isArray(U,D+"."+U,!0,!0)?F[U]=[E[U]]:F[U]=E[U]}}}s(j,"assignAttributes"),r(j,"assignAttributes");function Z(F,E){let{textNodeName:D}=E,V=Object.keys(F).length;return!!(V===0||V===1&&(F[D]||typeof F[D]=="boolean"||F[D]===0))}s(Z,"isLeafTag"),r(Z,"isLeafTag"),P.prettify=S}}),g=o({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var S=a(),H={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,C){C=Object.assign({},H,C);let z=[],ae=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let I=0;I<b.length;I++)if(b[I]==="<"&&b[I+1]==="?"){if(I+=2,I=j(b,I),I.err)return I}else if(b[I]==="<"){let A=I;if(I++,b[I]==="!"){I=Z(b,I);continue}else{let B=!1;b[I]==="/"&&(B=!0,I++);let L="";for(;I<b.length&&b[I]!==">"&&b[I]!==" "&&b[I]!==" "&&b[I]!==`
63
- `&&b[I]!=="\r";I++)L+=b[I];if(L=L.trim(),L[L.length-1]==="/"&&(L=L.substring(0,L.length-1),I--),!W(L)){let q;return L.trim().length===0?q="Invalid space after '<'.":q="Tag '"+L+"' is an invalid name.",U("InvalidTag",q,X(b,I))}let _=D(b,I);if(_===!1)return U("InvalidAttr","Attributes for '"+L+"' have open quote.",X(b,I));let Q=_.value;if(I=_.index,Q[Q.length-1]==="/"){let q=I-Q.length;Q=Q.substring(0,Q.length-1);let N=G(Q,C);if(N===!0)ae=!0;else return U(N.err.code,N.err.msg,X(b,q+N.err.line))}else if(B)if(_.tagClosed){if(Q.trim().length>0)return U("InvalidTag","Closing tag '"+L+"' can't have attributes or invalid starting.",X(b,A));{let q=z.pop();if(L!==q.tagName){let N=X(b,q.tagStartPos);return U("InvalidTag","Expected closing tag '"+q.tagName+"' (opened in line "+N.line+", col "+N.col+") instead of closing tag '"+L+"'.",X(b,A))}z.length==0&&(R=!0)}}else return U("InvalidTag","Closing tag '"+L+"' doesn't have proper closing.",X(b,I));else{let q=G(Q,C);if(q!==!0)return U(q.err.code,q.err.msg,X(b,I-Q.length+q.err.line));if(R===!0)return U("InvalidXml","Multiple possible root nodes found.",X(b,I));C.unpairedTags.indexOf(L)!==-1||z.push({tagName:L,tagStartPos:A}),ae=!0}for(I++;I<b.length;I++)if(b[I]==="<")if(b[I+1]==="!"){I++,I=Z(b,I);continue}else if(b[I+1]==="?"){if(I=j(b,++I),I.err)return I}else break;else if(b[I]==="&"){let q=x(b,I);if(q==-1)return U("InvalidChar","char '&' is not expected.",X(b,I));I=q}else if(R===!0&&!k(b[I]))return U("InvalidXml","Extra text at the end",X(b,I));b[I]==="<"&&I--}}else{if(k(b[I]))continue;return U("InvalidChar","char '"+b[I]+"' is not expected.",X(b,I))}if(ae){if(z.length==1)return U("InvalidTag","Unclosed tag '"+z[0].tagName+"'.",X(b,z[0].tagStartPos));if(z.length>0)return U("InvalidXml","Invalid '"+JSON.stringify(z.map(I=>I.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return U("InvalidXml","Start tag expected.",1);return!0};function k(b){return b===" "||b===" "||b===`
64
- `||b==="\r"}s(k,"isWhiteSpace"),r(k,"isWhiteSpace");function j(b,C){let z=C;for(;C<b.length;C++)if(b[C]=="?"||b[C]==" "){let ae=b.substr(z,C-z);if(C>5&&ae==="xml")return U("InvalidXml","XML declaration allowed only at the start of the document.",X(b,C));if(b[C]=="?"&&b[C+1]==">"){C++;break}else continue}return C}s(j,"readPI"),r(j,"readPI");function Z(b,C){if(b.length>C+5&&b[C+1]==="-"&&b[C+2]==="-"){for(C+=3;C<b.length;C++)if(b[C]==="-"&&b[C+1]==="-"&&b[C+2]===">"){C+=2;break}}else if(b.length>C+8&&b[C+1]==="D"&&b[C+2]==="O"&&b[C+3]==="C"&&b[C+4]==="T"&&b[C+5]==="Y"&&b[C+6]==="P"&&b[C+7]==="E"){let z=1;for(C+=8;C<b.length;C++)if(b[C]==="<")z++;else if(b[C]===">"&&(z--,z===0))break}else if(b.length>C+9&&b[C+1]==="["&&b[C+2]==="C"&&b[C+3]==="D"&&b[C+4]==="A"&&b[C+5]==="T"&&b[C+6]==="A"&&b[C+7]==="["){for(C+=8;C<b.length;C++)if(b[C]==="]"&&b[C+1]==="]"&&b[C+2]===">"){C+=2;break}}return C}s(Z,"readCommentAndCDATA"),r(Z,"readCommentAndCDATA");var F='"',E="'";function D(b,C){let z="",ae="",R=!1;for(;C<b.length;C++){if(b[C]===F||b[C]===E)ae===""?ae=b[C]:ae!==b[C]||(ae="");else if(b[C]===">"&&ae===""){R=!0;break}z+=b[C]}return ae!==""?!1:{value:z,index:C,tagClosed:R}}s(D,"readAttributeStr"),r(D,"readAttributeStr");var V=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function G(b,C){let z=S.getAllMatches(b,V),ae={};for(let R=0;R<z.length;R++){if(z[R][1].length===0)return U("InvalidAttr","Attribute '"+z[R][2]+"' has no space in starting.",Te(z[R]));if(z[R][3]!==void 0&&z[R][4]===void 0)return U("InvalidAttr","Attribute '"+z[R][2]+"' is without value.",Te(z[R]));if(z[R][3]===void 0&&!C.allowBooleanAttributes)return U("InvalidAttr","boolean attribute '"+z[R][2]+"' is not allowed.",Te(z[R]));let I=z[R][2];if(!se(I))return U("InvalidAttr","Attribute '"+I+"' is an invalid name.",Te(z[R]));if(!ae.hasOwnProperty(I))ae[I]=1;else return U("InvalidAttr","Attribute '"+I+"' is repeated.",Te(z[R]))}return!0}s(G,"validateAttributeString"),r(G,"validateAttributeString");function v(b,C){let z=/\d/;for(b[C]==="x"&&(C++,z=/[\da-fA-F]/);C<b.length;C++){if(b[C]===";")return C;if(!b[C].match(z))break}return-1}s(v,"validateNumberAmpersand"),r(v,"validateNumberAmpersand");function x(b,C){if(C++,b[C]===";")return-1;if(b[C]==="#")return C++,v(b,C);let z=0;for(;C<b.length;C++,z++)if(!(b[C].match(/\w/)&&z<20)){if(b[C]===";")break;return-1}return C}s(x,"validateAmpersand"),r(x,"validateAmpersand");function U(b,C,z){return{err:{code:b,msg:C,line:z.line||z,col:z.col}}}s(U,"getErrorObject"),r(U,"getErrorObject");function se(b){return S.isName(b)}s(se,"validateAttrName"),r(se,"validateAttrName");function W(b){return S.isName(b)}s(W,"validateTagName"),r(W,"validateTagName");function X(b,C){let z=b.substring(0,C).split(/\r?\n/);return{line:z.length,col:z[z.length-1].length+1}}s(X,"getLineNumberForPosition"),r(X,"getLineNumberForPosition");function Te(b){return b.startIndex+b[1].length}s(Te,"getPositionFromMatch"),r(Te,"getPositionFromMatch")}}),f=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,S){var{buildOptions:H}=i(),k=d(),{prettify:j}=p(),Z=g(),F=class{static{s(this,"XMLParser")}static{r(this,"XMLParser")}constructor(E){this.externalEntities={},this.options=H(E)}parse(E,D){if(typeof E!="string")if(E.toString)E=E.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(D){D===!0&&(D={});let v=Z.validate(E,D);if(v!==!0)throw Error(`${v.err.msg}:${v.err.line}:${v.err.col}`)}let V=new k(this.options);V.addExternalEntities(this.externalEntities);let G=V.parseXml(E);return this.options.preserveOrder||G===void 0?G:j(G,this.options)}addEntity(E,D){if(D.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(E.indexOf("&")!==-1||E.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(D==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[E]=D}};S.exports=F}});let O=f();return new O(n)},"getXmlParser");var Zo=class extends Fe{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),h("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?it(e.parseOnStatusCodes):void 0,this.parser=ia({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 u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new M(c)}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 qo=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new K(`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 Fo=class{static{s(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new J(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),mn().waitUntil(this.#e.waitUntilFlushed())}};var sa=10,aa=3e4,$o=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=aa,this.#r=sa}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:aa,this.#r=sa}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await bl(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#u(e);if(r)return r}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);mn().waitUntil(t)}}async#c(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 Error(`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 bl(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}s(bl,"waitUntilTrue");var jo=["sha-1","sha-256","sha-384","sha-512"],On=class{static{s(this,"BaseCryptoBeta")}};var Bo=class extends On{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(!jo.includes(e.toLowerCase()))throw new M(`Algorithm ${e} is not supported. Try using ${jo.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var An=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var zo=class extends An{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=y.instance.runtime.ZUPLO_KV;if(!t)throw new Wo("The Key Value Store feature is not enabled for this project.");this.#e=t,h("platform.kv-store")}put(e,t,r){if(typeof e!="string")throw new m("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{Kr as AWSLoggingPlugin,Vu as AmberfloMeteringInboundPolicy,fo as AmberfloMeteringPolicy,Ku as ApiAuthKeyInboundPolicy,ho as ApiKeyInboundPolicy,io as AuditLogDataStaxProvider,so as AuditLogPlugin,ec as Auth0JwtInboundPolicy,pu as AwsLambdaHandlerExtensions,Ro as AxiomaticsAuthZInboundPolicy,Fo as BackgroundDispatcher,$o as BackgroundLoader,tc as BasicAuthInboundPolicy,Ws as BasicRateLimitInboundPolicy,J as BatchDispatch,Eo as BrownoutInboundPolicy,pc as CachingInboundPolicy,mc as ChangeMethodInboundPolicy,gc as ClearHeadersInboundPolicy,fc as ClearHeadersOutboundPolicy,hc as ClerkJwtInboundPolicy,yc as CognitoJwtInboundPolicy,So as ComplexRateLimitInboundPolicy,Tc as CompositeInboundPolicy,m as ConfigurationError,nr as ContentTypes,he as ContextData,Bo as CryptoBeta,vc as CurityPhantomTokenInboundPolicy,Sr as DataDogLoggingPlugin,Xr as DataDogMetricsPlugin,qr as DynaTraceLoggingPlugin,no as DynatraceMetricsPlugin,Cc as FirebaseJwtInboundPolicy,Oc as FormDataToJsonInboundPolicy,Ac as GeoFilterInboundPolicy,Ir as GoogleCloudLoggingPlugin,kr as Handler,T as HttpProblems,Kt as HttpStatusCode,pe as InboundPolicy,Lc as JWTScopeValidationInboundPolicy,zo as KeyValueStore,$r as LokiLoggingPlugin,Ht as LookupResult,ue as MemoryZoneReadThroughCache,kc as MockApiInboundPolicy,Zc as MoesifInboundPolicy,Lo as MonetizationInboundPolicy,Fc as OktaJwtInboundPolicy,ye as OpenIdJwtInboundPolicy,Fe as OutboundPolicy,Ke as ProblemResponseFormatter,jc as PropelAuthJwtInboundPolicy,Ws as RateLimitInboundPolicy,Gc as ReadmeMetricsInboundPolicy,Wc as RemoveHeadersInboundPolicy,Kc as RemoveHeadersOutboundPolicy,Jc as RemoveQueryParamsInboundPolicy,Yc as ReplaceStringOutboundPolicy,Xc as RequestSizeLimitInboundPolicy,na as RequestValidationInboundPolicy,el as RequireOriginInboundPolicy,vt as ResponseSendingEvent,St as ResponseSentEvent,Ut as Router,M as RuntimeError,Bt as SYSTEM_LOGGER,Qc as SchemaBasedRequestValidation,Le as SemanticAttributes,qo as ServiceProviderImpl,tl as SetBodyInboundPolicy,nl as SetHeadersInboundPolicy,rl as SetHeadersOutboundPolicy,ol as SetQueryParamsInboundPolicy,il as SetStatusOutboundPolicy,al as SleepInboundPolicy,Is as StripeMonetizationPlugin,qt as StripeWebhookVerificationInboundPolicy,zr as SumoLogicLoggingPlugin,ul as SupabaseJwtInboundPolicy,Ue as SystemRouteName,Et as TelemetryPlugin,cl as UpstreamAzureAdServiceAuthInboundPolicy,dl as UpstreamFirebaseAdminAuthInboundPolicy,gl as UpstreamFirebaseUserAuthInboundPolicy,fl as UpstreamGcpJwtInboundPolicy,hl as UpstreamGcpServiceAuthInboundPolicy,Gr as VMWareLogInsightLoggingPlugin,yl as ValidateJsonSchemaInbound,Zo as XmlToJsonOutboundPolicy,Pt as ZoneCache,ee as ZuploRequest,mu as awsLambdaHandler,be as environment,_n as getIdForParameterSchema,ca as getIdForRefSchema,Nn as getIdForRequestBodySchema,ua as getRawOperationDataIdentifierName,or as httpStatuses,Pu as openApiSpecHandler,Eu as redirectHandler,la as sanitizedIdentifierName,rr as serialize,Mc as setMoesifContext,h as trackFeature,Tu as urlForwardHandler,Su as urlRewriteHandler,Cu as webSocketHandler,Ou as webSocketPipelineHandler};
61
+ `+d});let p=Math.floor((typeof u=="number"?u:Date.now())/1e3)-t.timestamp;if(o>0&&p>o)throw new Ne(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(Ku,"validateComputedSignature");function Ju(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(Ju,"parseHeader");function Xu(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(Xu,"secureCompare");async function Yu(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 u=0;u<i.length;u++)a[u]=go[i[u]];return a.join("")}s(Yu,"computeHMACSignatureAsync");var go=new Array(256);for(let n=0;n<go.length;n++)go[n]=n.toString(16).padStart(2,"0");function Y(n,e,t="policy",r){let o=`${t} '${e}'`;if(!Je(n))throw new m(`Options on ${o} is expected to be an object. Received the type '${typeof n}'.`);let i=s((c,l,d)=>{let p=n[c],f=r?`${r}.${String(c)}`:String(c);if(!(d&&p===void 0)){if(p===void 0)throw new m(`Value of '${f}' 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 m(`Value of '${f}' on ${o} must be an array. Received type ${typeof p}.`);if(typeof p!==l)throw new m(`Value of '${f}' on ${o} must be of type ${l}. Received type ${typeof p}.`);if(typeof p=="string"&&p.length===0)throw new m(`Value of '${f}' 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 m(`Value of '${f}' on ${o} must be valid number. If using an environment variable, check that it is set correctly.`)}},"validate"),a=s((c,l)=>(i(c,l,!0),{optional:a,required:u}),"optional"),u=s((c,l)=>(i(c,l,!1),{optional:a,required:u}),"required");return{optional:a,required:u}}s(Y,"optionValidator");var Ft=class extends de{static{s(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),g("policy.inbound.stripe-webhook-verification")}async handler(e,t){Y(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 Rs(o,r,this.options.signingSecret)}catch(o){let i=o.message;if(o.type&&o.type==="StripeSignatureVerificationError"){let a=o.message,c=/Note:(.*)/g.exec(a);i=c?c[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),x.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function Ps(n){return n!==null&&typeof n=="object"&&"id"in n&&Ie(n.id)&&"type"in n&&Ie(n.type)}s(Ps,"isStripeWebhookEvent");var Qu={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await F.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 _(i)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.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 _(i)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await F.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 _(i)}return o}},Rn=Qu;var fo="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",Is="My API Key";async function Es({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=y.instance,c=new URL(`/v1/buckets/${n}/consumers`,fo);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:Is,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await ge({retryDelayMs:5,retries:2,logger:X.getLogger(a)},c.toString(),{method:"POST",headers:{Authorization:`Bearer ${u}`,"content-type":"application/json"},body:JSON.stringify(d)}),f=await p.json();if(p.status!==200){let h="Error creating API Key Consumer";throw a.log.error(h,f),new _(h)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}s(Es,"createConsumer");async function xs({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=y.instance,u=new URL(`/v1/buckets/${n}/consumers`,fo);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:Is,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await ge({retryDelayMs:5,retries:2,logger:X.getLogger(i)},u.toString(),{method:"POST",headers:{Authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify(l)}),p=await d.json();if(d.status!==200){let f="Error creating API Key Consumer";throw i.log.error(f,p),new _(f)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}s(xs,"createConsumerInvite");async function Ts({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=y.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,fo);o.searchParams.set("with-api-key","true");let i=await ge({retryDelayMs:5,retries:2,logger:X.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(),u="Error invalidating API Key Consumer";throw t.log.error(u,a),new _(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(Ts,"deleteConsumer");async function vs({context:n,stripeSubscriptionId:e,stripeProductId:t,customerKey:r,meteringBucketId:o,meteringBucketRegion:i,customerExternalId:a,subscriptionStatus:u,metadata:c,trial:l}){let d={status:u,type:"periodic",renewalStrategy:"monthly",region:i,subscriptionExternalId:e,planExternalIds:[t],customerKey:r,customerExternalId:a,metadata:c,trialEndDate:l?l.trialEndDate:void 0,trialStartDate:l?l.trialStartDate:void 0,trialEndStatus:l?l.trialEndStatus:void 0},{authApiJWT:p,meteringServiceUrl:f}=y.instance;if(!ot(p))throw new W("No Zuplo JWT token set.");let h=await ge({retryDelayMs:5,retries:2,logger:X.getLogger(n)},`${f}/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 O=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,P,S="";try{P=await h.json(),S=P.detail??P.title}catch{P={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:h.status,detail:h.statusText}}throw n.log.error(O,P),new _(`${O} ${S}`)}n.log.info("Successfully created monetization subscription.",d)}s(vs,"createSubscription");async function lt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!ot(o))throw new W("No Zuplo JWT token set.");let a=await ge({retryDelayMs:5,retries:2,logger:X.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 u=`Unable to update monetization subscription with: '${JSON.stringify(r)}'.`,c,l="";try{c=await a.json(),l=c.detail??c.title}catch{c={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:a.status,detail:a.statusText}}throw n.log.error(u,c),new _(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}s(lt,"updateSubscription");async function dt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=y.instance;if(!ot(o))throw new W("No Zuplo JWT token set.");let a=await ge({retryDelayMs:5,retries:2,logger:X.getLogger(n)},`${i}/internal/v1/metering/${r}/subscriptions?subscriptionExternalId=${e}`,{headers:{Authorization:`Bearer ${o}`,"zp-rid":n.requestId},method:"GET"});if(!a.ok){let c=`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(c,l),new _(`${c} ${d}`)}let u=await a.json();if(u.data.length===0){let c=`Subscription was not found for Stripe subscription '${e}' and the event was ignored by Zuplo.`;throw n.log.error(c),new _(c)}if(u.data[0].customerExternalId!==t){let c=`Subscription was not found for Stripe customer '${t}' and the event was ignored by Zuplo.`;throw n.log.error(c),new _(c)}return u.data[0]}s(dt,"getSubscription");var re="Skipping since we're unable to process the webhook event.",ze="Successfully processed the webhook event",Pe="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function Pn(n){return n.replaceAll("_","-")}s(Pn,"stripeStatusToMeteringStatus");function et(n){return new Date(n*1e3).toISOString()}s(et,"unixTimestampToISOString");async function ho(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.`),x.ok(n,e,{title:re,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.`),x.ok(n,e,{title:re,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}'`),x.ok(n,e,{title:re,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}'.`),x.ok(n,e,{title:re,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.`+Pe});let u=i.product,c,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,c=await Es({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await Rn.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.`),x.ok(n,e,{title:re,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await xs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:p.email,context:e})}}catch(p){return e.log.warn(`Failed to create API Key Consumer. Error: ${p.message}`),x.ok(n,e,{title:re,detail:p.message})}if(!c)return x.ok(n,e,{title:re,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=Pn(t.data.object.status),f;l&&d&&(f={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:et(t.data.object.trial_end),trialStartDate:et(t.data.object.trial_start)}),await vs({context:e,stripeProductId:u,stripeSubscriptionId:o,customerKey:c,meteringBucketId:r.meteringBucketId,meteringBucketRegion:r.meteringBucketRegion,customerExternalId:a,subscriptionStatus:p,metadata:f,trial:h})}catch(p){return await Ts({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:re,detail:p.message})}return x.ok(n,e,{title:ze})}s(ho,"onCustomerSubscriptionCreated");async function yo(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.`),x.ok(n,e,{title:re,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}'`),x.ok(n,e,{title:re,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}'.`),x.ok(n,e,{title:re,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.`+Pe});try{let a=await dt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await lt({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:re,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. `+Pe})}return x.ok(n,e,{title:ze})}s(yo,"onCustomerSubscriptionDeleted");async function bo(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.`),x.ok(n,e,{title:re,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}'`),x.ok(n,e,{title:re,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}'.`),x.ok(n,e,{title:re,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.`+Pe});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 u=await dt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=Pn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=et(t.data.object.trial_end)),await lt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.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. `+Pe})}return x.ok(n,e,{title:ze})}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 u=await dt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await Rn.getUpcomingInvoice({customerId:i,logger:e.log,stripeSecretKey:r.stripeSecretKey})).lines.data.filter(f=>f.proration&&f.price.product===c),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 lt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.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. `+Pe})}return x.ok(n,e,{title:ze})}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 u=await dt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?et(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?et(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await lt({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:u.planExternalIds,metadata:l}})}catch(u){return x.ok(n,e,{title:re,detail:`The event 'customer.subscription.updated' could not be processed. ${u.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. `+Pe})}return x.ok(n,e,{title:ze})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:re,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."+Pe})}s(bo,"onCustomerSubscriptionUpdated");var Ss=class extends Wt{constructor(t){super();this.options=t;g("monetization.stripe")}static{s(this,"StripeMonetizationPlugin")}registerRoutes(t,r){let o=s(async(c,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(we.ZUPLO_METERING_SERVICE_BUCKET_ID)d=we.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(we.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=we.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!y.instance.build.ACCOUNT_NAME)throw new W("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let f=this.options.primaryDataRegion??"us-central1";if(!ec(f))throw new m(`StripeMonetizationPlugin - The value '${f}' on the property 'primaryDataRegion' is invalid.`);let h=await c.json();if(!Ps(h))return x.ok(c,l,{title:re,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+Pe});switch(l.log.info(`Received Stripe webhook event of type '${h.type}' with ID '${h.id}'.`),h.type){case"customer.subscription.created":return await ho(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await bo(c,l,h,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:f,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await yo(c,l,h,{meteringBucketId:d});default:return x.ok(c,l,{title:re,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.`+Pe})}},"stripeWebhookHandler"),i=$i({inboundPolicies:[new Ft({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});Y(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new le({processors:[ye,i],handler:o,gateway:r}),u=new se({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function ec(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(ec,"isMetricsRegion");var Os=new WeakMap,Cs={},wo=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Os.set(e,t)}};async function tc(n,e,t,r){if(g("policy.inbound.amberflo-metering"),!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=it(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Os.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new _(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Xe(n.user,t.customerIdPropertyPath,"customerIdPropertyPath")}let c=a?.customerId??u;if(!c){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:c,meterApiName:l,meterValue:d,meterTimeInMillis:Date.now(),dimensions:Object.apply(t.dimensions??{},a?.dimensions)},f=Cs[t.apiKey];if(!f){let h=t.apiKey,O=n.headers.get("zm-test-id")??"";f=new J("amberflo-ingest-meter",10,async P=>{try{let S=t.url??"https://app.amberflo.io/ingest",H=await F.fetch(S,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":h,"zm-test-id":O}});H.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${H.status}: ${await H.text()}`)}catch(S){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${S.message}`),S}}),Cs[h]=f}f.enqueue(p),e.waitUntil(f.waitUntilFlushed())}}),n}s(tc,"AmberfloMeteringInboundPolicy");async function In(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(In,"sha256");var As=new Map;async function ce(n,e,t){let r,o=`${n}-${e}`,i=As.get(o);return i!==void 0?r=i:(r=`zuplo-policy-${await In(JSON.stringify({policyName:n,options:t}))}`,As.set(n,r)),r}s(ce,"getPolicyCacheName");var Ls="key-metadata-cache-type";function nc(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(nc,"getKeyValue");async function Ro(n,e,t,r){if(g("policy.inbound.api-key"),!t.bucketName)if(we.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=we.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m(`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 m(`ApiKeyInboundPolicy '${r}' - minimum cacheTtlSeconds value is 60s, '${o.cacheTtlSeconds}' is invalid`);let i=s(S=>o.allowUnauthenticatedRequests?n:x.unauthorized(n,e,{detail:S}),"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 u=nc(a,o);if(!u||u==="")return i("No key present");let c=await rc(u),l=await ce(r,void 0,o),d=new ie(l,e),p=await d.get(c);if(p&&p.isValid===!0)return n.user=p.user,n;if(p&&!p.isValid)return p.typeId!==Ls&&X.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let f={key:u},h=await ge({retryDelayMs:5,retries:2,logger:X.getLogger(e)},`${y.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":y.instance.deploymentName??"unknown","User-Agent":y.instance.systemUserAgent},body:JSON.stringify(f)});if(h.status===401)return e.log.info(`ApiKeyInboundPolicy '${r}' - 401 response from Key Service`),i("Authorization Failed");if(h.status!==200){try{let S=await h.text(),H=JSON.parse(S);e.log.error("Unexpected response from key service",H)}catch{e.log.error("Invalid response from key service")}throw new _(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${h.status}`)}let O=await h.json(),P={isValid:!0,typeId:Ls,user:{sub:O.name,data:O.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}s(Ro,"ApiKeyInboundPolicy");async function rc(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(rc,"hashValue");var oc=Ro;import{createRemoteJWKSet as sc,jwtVerify as _s}from"jose";import{createLocalJWKSet as ic}from"jose";var Po=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 Io&&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=ic(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,u=!1;typeof AbortController=="function"&&(i=new AbortController,a=setTimeout(()=>{u=!0,i.abort()},t));let c=await F.fetch(e.href,{signal:i?i.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new Eo("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new pt("Expected 200 OK from the JSON Web Key Set HTTP response");try{let l=await c.json();return this.cache.put(this.url.href,l,this.cacheMaxAge),l}catch{throw new pt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function ks(n,e,t){let r=new Po(n,e,t);return async(o,i)=>r.getKey(o,i)}s(ks,"createRemoteJWKSet");var pt=class extends _{static{s(this,"JWKSError")}},Io=class extends pt{static{s(this,"JWKSNoMatchingKey")}},Eo=class extends pt{static{s(this,"JWKSTimeout")}};var En={},ac=s((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!En[r.jwkUrl]){let i=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(i=r.useExperimentalInMemoryCache),i){let a=await ce(n,void 0,r),u=new ie(a,e);En[r.jwkUrl]=ks(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else En[r.jwkUrl]=sc(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await _s(t,En[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),uc=s(async(n,e)=>{let t;if(e.secret===void 0)throw new Error("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 _s(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),be=s(async(n,e,t,r)=>{g("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),i="bearer ",a=s(f=>x.unauthorized(n,e,{detail:f}),"unauthorizedResponse");if(!t.jwkUrl&&!t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': One of 'jwkUrl' or 'secret' options are required.`);if(t.jwkUrl&&t.secret)throw new m(`OpenIdJwtInboundPolicy policy '${r}': Only one of 'jwkUrl' and 'secret' options should be provided.`);let u=t.jwkUrl?ac(r,e):uc,l=await s(async()=>{if(!o)return a("No authorization header");if(o.toLowerCase().indexOf(i)!==0)return a("Invalid bearer token format for authorization header");let f=o.substring(i.length);if(!f||f.length===0)return a("No bearer token on authorization header");try{return await u(f,t)}catch(h){let O=new URL(n.url);return"code"in h&&h.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${O.pathname} `,h):e.log.warn(`Invalid token on: ${n.method} ${O.pathname}`,h),a("Invalid token")}},"getJwtOrRejectedResponse")();if(l instanceof Response)return t.allowUnauthenticatedRequests===!0?n:l;let d=t.subPropertyName??"sub",p=l[d];return p?(n.user={sub:p,data:l},n):a(`Token is not valid, no '${d}' property found.`)},"OpenIdJwtInboundPolicy");var cc=s(async(n,e,t,r)=>(g("policy.inbound.auth0-jwt-auth"),be(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var xo=class n extends de{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"),Y(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new ei(e)}async handler(e,t){let r=s(a=>this.options.allowUnauthorizedRequests?e:x.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(([u,c])=>{a.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.push({AttributeId:`request.query.${c}`,Value:u})}),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(u=>u.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),x.internalServerError(e,t)}}populateOptionAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,context:o}){let i=this.options[e];if(i){let a=[];i.forEach(u=>{u.value?a.push({AttributeId:u.attributeId,Value:u.value}):o.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${u.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 lc=s(async(n,e,t)=>{g("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",i=s(l=>x.unauthorized(n,e,{detail:l}),"unauthorizedResponse"),u=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 f=d.substring(0,p),h=d.substring(p+1),O=t.accounts.find(P=>P.username===f&&P.password===h);return O||await i("Invalid username or password")},"getAccountOrRejectedResponse")();if(u instanceof Response)return t.allowUnauthenticatedRequests?n:u;let c=u.username;return n.user={sub:c,data:u.data},n},"BasicAuthInboundPolicy");function xn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(xn,"extractDateElements");function Ns(n,e){return new Date(n,e+1,0).getDate()}s(Ns,"getDaysInMonth");function To(n,e){return n<=e?e-n:6-n+e+1}s(To,"getDaysBetweenWeekdays");var Tn=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((c,l)=>c-l),this.minutes=Array.from(t).sort((c,l)=>c-l),this.hours=Array.from(r).sort((c,l)=>c-l),this.days=Array.from(o).sort((c,l)=>c-l),this.months=Array.from(i).sort((c,l)=>c-l),this.weekdays=Array.from(a).sort((c,l)=>c-l);let u=s((c,l,d)=>{if(l.some(p=>typeof p!="number"||p%1!==0||p<d.min||p>d.max))throw new Error(`${c} must only consist of integers which are within the range of ${d.min} and ${d.max}`)},"validateData");u("seconds",this.seconds,{min:0,max:59}),u("minutes",this.minutes,{min:0,max:59}),u("hours",this.hours,{min:0,max:23}),u("days",this.days,{min:1,max:31}),u("months",this.months,{min:0,max:11}),u("weekdays",this.weekdays,{min:0,max:6}),this.reversed={seconds:this.seconds.map(c=>c).reverse(),minutes:this.minutes.map(c=>c).reverse(),hours:this.hours.map(c=>c).reverse(),days:this.days.map(c=>c).reverse(),months:this.months.map(c=>c).reverse(),weekdays:this.weekdays.map(c=>c).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=Ns(t,r),a=this.days.length!==31,u=this.weekdays.length!==7;if(!a&&!u)return o>i?e==="next"?void 0:i:o;let c;a&&(c=e==="next"?this.days.find(d=>d>=o):this.reversed.days.find(d=>d<=o),c!==void 0&&c>i&&(c=void 0));let l;if(u){let d=new Date(t,r,o).getDay(),p=e==="next"?this.weekdays.find(f=>f>=d)??this.weekdays[0]:this.reversed.weekdays.find(f=>f<=d)??this.reversed.weekdays[0];if(p!==void 0){let f=e==="next"?To(d,p):To(p,d);l=e==="next"?o+f:o-f,(l>i||l<1)&&(l=void 0)}}if(c!==void 0&&l!==void 0)return e==="next"?Math.min(c,l):Math.max(c,l);if(c!==void 0)return c;if(l!==void 0)return l}getNextDate(e=new Date){let t=xn(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 u=r+Math.floor((o+a)/this.months.length),c=this.months[(o+a)%this.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("next",u,c,l?t.day:1),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("next",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d=this.findAllowedDayInMonth("next",u,c,d+1),p=!1}if(d!==void 0&&!p)return new Date(u,c,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=xn(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 u=r-Math.floor((o+a)/this.reversed.months.length),c=this.reversed.months[(o+a)%this.reversed.months.length],l=u===t.year&&c===t.month,d=this.findAllowedDayInMonth("prev",u,c,l?t.day:31),p=l&&d===t.day;if(d!==void 0&&p){let f=this.findAllowedTime("prev",t);if(f!==void 0)return new Date(u,c,d,f.hour,f.minute,f.second);d>1&&(d=this.findAllowedDayInMonth("prev",u,c,d-1),p=!1)}if(d!==void 0&&!p)return new Date(u,c,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:u}=xn(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(u)!==-1:this.days.indexOf(i)!==-1&&this.weekdays.indexOf(u)!==-1}};var dc={min:0,max:59},pc={min:0,max:59},mc={min:0,max:23},gc={min:1,max:31},fc={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"}},hc={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},yc={"@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 tt(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=>{tt(d,e).forEach(f=>t.add(f))}),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]),u=i[1]==="*"?e.max:o(i[4]);if(a>u)throw new Error(`Failed to parse ${n}: Invalid range (start: ${a}, end: ${u}).`);let c=i[6],l=1;if(c!==void 0){if(l=parseInt(c,10),Number.isNaN(l))throw new Error(`Failed to parse step: ${c} is NaN.`);if(l<1)throw new Error(`Failed to parse step: Expected ${c} to be greater than 0.`)}for(let d=a;d<=u;d=d+l)t.add(d);return t}s(tt,"parseElement");function vo(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=yc[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],u=e.length===6?e[5]:e[4];return new Tn({seconds:tt(t,dc),minutes:tt(r,pc),hours:tt(o,mc),days:tt(i,gc),months:new Set(Array.from(tt(a,fc)).map(c=>c-1)),weekdays:new Set(Array.from(tt(u,hc)).map(c=>c%7))})}s(vo,"parseCronExpression");var So=class extends de{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),g("policy.inbound.brownout"),Y(e,t).optional("problem","object"),e.problem&&Y(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 m(`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=[vo(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>vo(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=x.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 x.format(i,e,t)}return e}};var bc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function wc(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(wc,"digestMessage");var Rc=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 wc(JSON.stringify(r)),i=new URL(n.url),a=new URLSearchParams(i.searchParams);a.set("_z-hdr-dgst",o);let u=e.cacheHttpMethods?.includes(n.method.toUpperCase())&&n.method.toUpperCase()!=="GET";u&&a.set("_z-original-method",n.method);let c=`${i.origin}${i.pathname}?${a}`;return new Request(c,{method:u?"GET":n.method})},"createCacheKeyRequest");async function Pc(n,e,t,r){g("policy.inbound.caching");let o=await ce(r,t.cacheId,t),i=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await Rc(n,t),c=await i.match(u);return c||(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 f=t?.expirationSecondsTtl??60,h=new Response(p.body,p);bc.forEach(O=>h.headers.delete(O)),h.headers.set("cache-control",`s-maxage=${f}`),e.waitUntil(i.put(u,h))}catch(d){e.log.error(`Error in caching-inbound-policy '${r}': "${d.message}"`,d)}}),n)}s(Pc,"CachingInboundPolicy");var Ic=s(async(n,e,t,r)=>{if(g("policy.inbound.change-method"),!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new te(n,{method:t.method})},"ChangeMethodInboundPolicy");var Ec=s(async(n,e,t)=>{g("policy.inbound.clear-headers");let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new te(n,{headers:o})},"ClearHeadersInboundPolicy");var xc=s(async(n,e,t,r)=>{g("policy.outbound.clear-headers");let o=[...r.exclude??[]],i=new Headers;return o.forEach(u=>{let c=n.headers.get(u);c&&i.set(u,c)}),new Response(n.body,{headers:i,status:n.status,statusText:n.statusText})},"ClearHeadersOutboundPolicy");var Tc=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",be(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var vc=s(async(n,e,t,r)=>{if(g("policy.inbound.cognito-jwt-auth"),!t.userPoolId)throw new m("userPoolId must be set in the options for CognitoJwtInboundPolicy");if(!t.region)throw new m("region must be set in the options for CognitoJwtInboundPolicy");return be(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 qs=Be(Ve());var vn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},Co=class extends vn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Oo=class extends vn{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Sc(n,e){if(Ni(n))throw new Co(e)}s(Sc,"throwIfUndefinedOrNull");function $t(n,e){if(Sc(n,e),!Ie(n))throw new Oo(e,"string")}s($t,"throwIfNotString");var Sn=class n{static{s(this,"StandardRedisClient")}static instance;redisClientUrl;clientAuthToken;userAgent;deploymentName;constructor(e,t,r,o){this.redisClientUrl=e,this.clientAuthToken=t,this.deploymentName=r,this.userAgent=o}static initialize(e,t,r,o){return $t(e,"redisClientUrl"),$t(t,"clientAuthToken"),n.instance||(n.instance=new n(e,t,r,o)),n.instance}isEnabled(){return this.redisClientUrl!==void 0&&this.clientAuthToken!==void 0}async fetch({url:e,body:t,method:r,requestId:o}){$t(e,"url");let i=await F.fetch(`${this.redisClientUrl}${e}`,{method:r,body:t,headers:{"content-type":"application/json",authorization:`Bearer ${this.clientAuthToken}`,"zp-rid":o,"zp-dn":this.deploymentName,"User-Agent":this.userAgent}}),a=i.headers.get("Content-Type")?.includes("application/json")?await i.json():await i.text();if(i.ok)return a;throw i.status===401?new W("Rate limiting service failed with 401: Unauthorized"):new W(`Rate limiting service failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},Cn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if($t(e,"url"),r==="POST"&&e==="/rate-limit"){let{incrBy:o,expire:i,key:a}=JSON.parse(t),u=Date.now()+i*1e3,c=this.keyValueStore.get(a);c?Date.now()>c.expiresAt?this.keyValueStore.set(a,{value:o,expiresAt:u}):this.keyValueStore.set(a,{value:c.value+o,expiresAt:c.expiresAt}):this.keyValueStore.set(a,{value:o,expiresAt:u});let l=this.keyValueStore.get(a);return Promise.resolve({count:l.value,ttlSeconds:Math.round((l.expiresAt-Date.now())/1e3)})}throw new W("The in-memory rate limit client does not support this request")}};var Cc=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 mt(n,e){return{function:kc(e,"RateLimitInboundPolicy",n),user:Ac,ip:Oc,all:Lc}[e.rateLimitBy??"ip"]}s(mt,"getRateLimitByFunctions");var Oc=s(async n=>({key:`ip-${Cc(n)}`}),"getIP"),Ac=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Lc=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),On;function gt(n,e){let t;if(On)return On;if(!y.instance.authApiJWT)return e.info("Using in-memory rate limit client for local development."),t=new Cn,On=t,t;let{authApiJWT:r,redisURL:o}=y.instance;if(!Ie(o))throw new W(`RateLimitClient used in policy '${n}' - rate limit service URL not configured`);if(!Ie(r))throw new W(`RateLimitClient used in policy '${n}' - service authentication not configured`);if(o&&(t=Sn.initialize(o,r,y.instance.deploymentName??"unknown",y.instance.systemUserAgent)),!t||!t.isEnabled())throw new W(`RateLimitClient used in policy '${n}' - no remote rate limiting service enabled`);return On=t,t}s(gt,"getRedisClient");async function An(n,e,t,r){let o=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:o,key:n}),requestId:r})}s(An,"getCountAndUpdateExpiry");async function Ds(n,e,t){return(await e.fetch({url:"/rate-limits/check",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}s(Ds,"multiCount");async function Ms(n,e,t){return(await e.fetch({url:"/rate-limits/increment",method:"POST",body:JSON.stringify({limits:n}),requestId:t})).data}s(Ms,"multiIncrement");function kc(n,e,t){let r;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module||typeof n.identifier.module!="object")throw new m(`${e} '${t}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`${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 m(`${e} '${t}' - Custom rate limit function must be a valid function`)}return s(async(i,a,u)=>{let c=await r(i,a,u);if(!c||typeof c!="object"){let l=`${e} '${u}' - Custom rate limit function must return a valid object.`;throw a.log.error(l),new _(l)}if(!("key"in c)){let l=`${e} '${u}' - Custom rate limit function must return a valid key property.`;throw a.log.error(l,c),new _(l)}if(typeof c.key!="string"){let l=`${e} '${u}' - Custom rate limit function must return a valid key property of type string. Received type '${typeof c.key}'`;throw a.log.error(l),new _(l)}return c},"outerFunction")}s(kc,"wrapUserFunction");var ft="Retry-After";var Hs=(0,qs.debug)("zuplo:policies:ComplexRateLimitInboundPolicy"),Ao=Symbol("complex-rate-limit-counters"),Lo=class n extends de{static{s(this,"ComplexRateLimitInboundPolicy")}static setIncrements(e,t){let r=me.get(e,Ao)??{};Object.assign(r,t),me.set(e,Ao,t)}static getIncrements(e){return me.get(e,Ao)??{}}constructor(e,t){super(e,t),g("policy.inbound.complex-rate-limit-inbound"),Y(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&&Y(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 m(`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=X.getLogger(t),i=gt(this.policyName,o),a=s((c,l)=>{if(this.options.throwOnFailure)throw new W(c,{cause:l});o.error(c,l)},"throwOrLog"),u=s((c,l)=>{let d={};return(!c||c==="retry-after")&&(d[ft]=l.toString()),x.tooManyRequests(e,t,void 0,d)},"rateLimited");try{let l=await mt(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),f=(l.timeWindowMinutes??this.options.timeWindowMinutes??1)*60;t.addResponseSendingFinalHook(async()=>{try{let S=n.getIncrements(t);Hs(`ComplexRateLimitInboundPolicy '${this.policyName}' - increments ${JSON.stringify(S)}`);let H=Object.entries(p).map(([j])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${j}`,ttlSeconds:f,increment:S[j]??0})),k=Ms(H,i,t.requestId);t.waitUntil(k),await k}catch(S){t.log.error(S)}});let h=Object.entries(p).map(([S,H])=>({key:`complex-rate-limit${d}/${this.policyName}/${l.key}/${S}`,ttlSeconds:f,limit:H})),O=await Ds(h,i,t.requestId);return _c(O,h).length>0?u(this.options.headerMode??"retry-after",f):e}catch(c){return a(c.message,c),e}finally{let c=Date.now()-r;Hs(`ComplexRateLimitInboundPolicy '${this.policyName}' - latency ${c}ms`)}}};function _c(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(_c,"findOverLimits");var Nc=s(async(n,e,t,r)=>{if(g("policy.inbound.composite"),!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=fe.instance,i=Lt(t.policies,o?.routeData.policies);return Ir(i)(n,e)},"CompositeInboundPolicy");var Dc=s(async(n,e,t,r)=>{g("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let i=Mc(o);if(!i)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await ce(r,void 0,t),u=new ie(a,e),c=await u.get(i);if(!c){let l=await F.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)c=d,u.put(i,c,t.cacheDurationSeconds??600);else return l.status>=500?(e.log.error(`Error introspecting token - ${l.status}: '${d}'`),x.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):x.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function Mc(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(Mc,"getToken");var Hc=s(async(n,e,t,r)=>(g("policy.inbound.firebase-jwt-auth"),Y(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),be(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 qc=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 u={};for(let[d,p]of a)u[d]=p.toString();let c=new Headers(n.headers);return c.set("content-type","application/json"),c.delete("content-length"),new te(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var ht="__unknown__",Uc=s(async(n,e,t,r)=>{g("policy.inbound.geo-filter");let o={allow:{countries:bt(t.allow?.countries,"allow.countries",r),regionCodes:bt(t.allow?.regionCodes,"allow.regionCode",r),asns:bt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:bt(t.block?.countries,"block.countries",r),regionCodes:bt(t.block?.regionCodes,"block.regionCode",r),asns:bt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??ht,a=e.incomingRequestProperties.regionCode?.toLowerCase()??ht,u=e.incomingRequestProperties.asn?.toString()??ht,c=o.ignoreUnknown&&i===ht,l=o.ignoreUnknown&&a===ht,d=o.ignoreUnknown&&u===ht,p=o.allow.countries,f=o.allow.regionCodes,h=o.allow.asns;if(p.length>0&&!p.includes(i)&&!c||f.length>0&&!f.includes(a)&&!l||h.length>0&&!h.includes(u)&&!d)return yt(n,e,r,i,a,u);let O=o.block.countries,P=o.block.regionCodes,S=o.block.asns;return O.length>0&&O.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||S.length>0&&S.includes(u)&&!d?yt(n,e,r,i,a,u):n},"GeoFilterInboundPolicy");function yt(n,e,t,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),x.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(yt,"blockedResponse");function bt(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 m(`Invalid '${e}' for GeoFilterInboundPolicy '${t}': '${n}', must be a string or string[]`)}s(bt,"toLowerStringArray");var Zc=s(async(n,e,t)=>{g("policy.inbound.jwt-scope-validation");let r=n.user?.data.scope.split(" ")||[];if(!s((i,a)=>a.every(u=>i.includes(u)),"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 Fc=s(async(n,e,t,r)=>{g("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return ko(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 ko(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(u=>{o[u].content&&Object.keys(o[u].content).forEach(l=>{let d=o[u].content[l].examples;d&&Object.keys(d).forEach(f=>{a.push({responseName:u,contentName:l,exampleName:f,exampleValue:d[f]})})})}),a=a.filter(u=>!(t.responsePrefixFilter&&!u.responseName.startsWith(t.responsePrefixFilter)||t.contentType&&u.contentName!==t.contentType||t.exampleName&&u.exampleName!==t.exampleName)),t.random&&a.length>1){let u=Math.floor(Math.random()*a.length);return Us(a[u])}else return a.length>0?Us(a[0]):ko(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 Us(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(Us,"generateResponse");var ko=s((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return x.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var $c="Incoming",jc={logRequestBody:!0,logResponseBody:!0};function Zs(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(Zs,"headersToObject");function Fs(){return new Date().toISOString()}s(Fs,"timestamp");var _o=new WeakMap,zc={};function Bc(n,e){let t=_o.get(n);t||(t=zc);let r=Object.assign({...t},e);_o.set(n,r)}s(Bc,"setMoesifContext");async function $s(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($s,"readBody");var Vc={},No;function js(){if(!No)throw new _("Invalid State - no _lastLogger");return No}s(js,"getLastLogger");function Gc(n){let e=Vc[n];return e||(e=new J("moesif-inbound",100,async t=>{let r=JSON.stringify(t);js().debug("posting",r);let o=await F.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||js().error({status:o.status,body:await o.text()})})),e}s(Gc,"getDispatcher");async function Wc(n,e,t,r){g("policy.inbound.moesif-analytics"),No=e.log;let o=Fs(),i=Object.assign(jc,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await $s(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Gc(i.applicationId),d=n.headers.get("true-client-ip"),p=_o.get(e)??{},f={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Zs(n.headers)},h=i.logResponseBody?await $s(u,e):void 0,O={time:Fs(),status:u.status,headers:Zs(u.headers),body:h},P={request:f,response:O,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:$c};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}s(Wc,"MoesifInboundPolicy");async function zs(n,e,t,r){let o=X.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=y.instance,u;try{let l=await F.fetch(`${a}/internal/v1/metering/${r}/subscriptions?customerKey=${e}`,{headers:{Authorization:`Bearer ${i}`,"zp-rid":n.requestId},method:"GET"});if(l.ok)u=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 c=u&&u.data&&u.data.length>0?u.data:void 0;return c&&c.length>1?c.sort((d,p)=>d.createdOn>p.createdOn?-1:1)[0]:c&&c[0]}s(zs,"loadSubscription");async function Bs(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=y.instance,u=X.getLogger(n);try{let c=await F.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(!c.ok){let l=await c.json(),d=l.detail??l.title??"Unknown error on quota consumption.";n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota. ${c.status} - ${d}`)}}catch(c){n.log.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`),u.error(`MonetizationInboundPolicy '${t}' - Error updating subscription quota.`,c)}}s(Bs,"consumeSubcriptionQuotas");var Kc=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Ln(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 m(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 m?new m(`MonetizationInboundPolicy '${e}' - The property 'meters' is invalid. ${t.message}`):t}}s(Ln,"validateMeters");function Vs(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=Ye(n),r=[];for(let o of t)Kc.has(o)||r.push(o);if(r.length>0)throw new m(`Found the following invalid statuses: ${r.join(", ")}`);return n}catch(t){throw t instanceof m?new m(`MonetizationInboundPolicy '${e}' - The property 'allowedSubscriptionStatuses' is invalid. ${t.message}`):t}else return["active","incomplete","trialing"]}s(Vs,"parseAllowedSubscriptionStatuses");function Gs(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(Gs,"compareMeters");var Do=class extends de{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return me.get(e,Et)}static setMeters(e,t){Ln(t,"setMeters"),me.set(e,Vt,t)}constructor(e,t){super(e,t),g("policy.inbound.monetization")}async handler(e,t){Y(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=it(this.options.meterOnStatusCodes),i=me.get(t,Vt),a={...this.options.meters,...i};Ln(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Vs(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,S,H)=>{let k=me.get(H,Et);if((this.options.allowRequestsWithoutSubscription??!1)&&!k){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(we.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=we.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let U=me.get(H,Vt),$={...this.options.meters,...U};if(Ln($,this.policyName),o.includes(P.status)&&k&&$){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${k.id}' with meters '${JSON.stringify($)} on response status '${P.status}'`);let{metersInSubscription:E,metersNotInSubscription:M}=Gs(k.meters,$);if(M&&Object.keys(M).length>0){let V=Object.keys(M);H.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${V}'`)}await Bs(H,k.id,this.policyName,this.options.bucketId,E)}});let l=e.user;if(!l)return u?e:x.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(we.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=we.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await zs(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:x.unauthorized(e,t,{detail:"No valid subscription found"});if(!c.includes(p.status)&&!u)return t.log.warn(`Subscription '${p.id}' has status '${p.status}' which is not part of the allowed statuses.`),x.unauthorized(e,t,{detail:"No valid subscription found"});c.includes(p.status)&&(t.log.debug(`Loading subscription '${p.id}' for user sub '${d}' to ContextData`),me.set(t,Et,p));let f=me.get(t,Et);if(!f)return u?e:(t.log.warn("Subscription is not available for user"),x.paymentRequired(e,t,{detail:"Subscription is not available for user",title:"No Subscription"}));if(f&&Object.keys(f.meters).length===0)return t.log.error(`Quota is not set up for subscription '${f.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let O=Object.keys(a).filter(P=>!Object.keys(f.meters).includes(P));if(O.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${O.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${O.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(f.meters[P].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};var Jc=s(async(n,e,t,r)=>(g("policy.inbound.okta-jwt-auth"),be(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");async function Ws(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 ge({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.",i)}catch{}throw new _("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 _("Response returned from identity provider is not in the expected format.")}s(Ws,"getClientCredentialsAccessToken");var wt=class extends Error{constructor(t,r,o){super(r,o);this.code=t}static{s(this,"OpenFGAError")}},kn=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 Error("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}`,u=new Request(a,{method:t,headers:i,body:o?JSON.stringify(o):void 0}),c=await F.fetch(u);if(c.status!==200){let l;try{l=await c.json()}catch{}throw!l||!l.code||!l.message?new wt("unknown",`Unknown error. Status: ${c.status}`):new wt(l.code,l.message)}return c.json()}};function jt(n,e,t){!n[e]&&t&&(n[e]=t)}s(jt,"setHeaderIfNotSet");var Ks="X-OpenFGA-Client-Method",Js="X-OpenFGA-Client-Bulk-Request-Id",zt=class extends kn{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 jt(r,Ks,"BatchCheck"),jt(r,Js,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 wt)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:u}=e,{headers:c={}}=t;if(jt(c,Ks,"ListRelations"),jt(c,Js,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:u})),Object.assign({},t,c)),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 Xs=Symbol("openfga-authz-context-data"),Mo=class extends de{static{s(this,"OpenFGAAuthZInboundPolicy")}client;authorizer;cache;static setContextChecks(e,t){let r=Array.isArray(t)?t:[t];me.set(e,Xs,r)}constructor(e,t){if(super(e,t),g("policy.inbound.openfga-authz"),Y(e,t).required("apiUrl","string").optional("storeId","string").optional("authorizationModelId","string"),!e.credentials)throw new m(`OpenFGAAuthZInboundPolicy '${this.policyName}' - The 'credentials' option is required.`);if(e.credentials.method==="client-credentials")Y(e.credentials,t).required("clientId","string").required("clientSecret","string").required("oauthTokenEndpointUrl","string").optional("apiAudience","string");else if(e.credentials.method==="api-token")Y(e.credentials,t).required("token","string").optional("headerName","string").optional("headerValuePrefix","string");else if(e.credentials.method==="header")Y(e.credentials,t).optional("headerName","string");else if(e.credentials.method!=="none")throw new m(`OpenFGAAuthZInboundPolicy '${this.policyName}' - The 'credentials.type' 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 zt({apiUrl:e.apiUrl,storeId:e.storeId,authorizationModelId:e.authorizationModelId})}async handler(e,t){if(!this.cache){let a=await ce(this.policyName,void 0,this.options);this.cache=new ie(a,t)}let r=s(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse"),o=me.get(t,Xs);if(!o||o.length===0)throw new _(`OpenFGAAuthZInboundPolicy '${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(u=>u.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),x.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 W(`OpenFGAAuthZInboundPolicy '${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 Ws({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 _("Invalid state for credentials method is not valid. This should not happen.")}};import{importSPKI as Xc}from"jose";var Ho,Yc=s(async(n,e,t,r)=>{if(g("policy.inbound.propel-auth-jwt-auth"),!Ho)try{Ho=await Xc(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return be(n,e,{issuer:t.authUrl,secret:Ho,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var na=Be(Ve());var Qs=Be(Ve());var Ys=(0,Qs.debug)("zuplo:policies:RateLimitInboundPolicy"),ea=s(async(n,e,t,r)=>{let o=X.getLogger(e),i=s(($,E)=>{let M={};return(!$||$==="retry-after")&&(M[ft]=E.toString()),x.tooManyRequests(n,e,void 0,M)},"rateLimited"),u=await mt(r,t)(n,e,r),c=u.key,l=u.requestsAllowed??t.requestsAllowed,d=u.timeWindowMinutes??t.timeWindowMinutes,p=t.headerMode??"retry-after",f=gt(r,o),O=`rate-limit${y.instance.isTestMode?y.instance.build.BUILD_ID:""}/${r}/${c}`,P=await ce(r,void 0,t),S=new ie(P,e),H=An(O,d,f,e.requestId),k;s(async()=>{let $=await H;if($.count>l){let E=Date.now()+$.ttlSeconds*1e3;S.put(O,E,$.ttlSeconds),Ys(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${O}' (async mode)`),k=i(p,$.ttlSeconds)}},"asyncCheck")();let U=await S.get(O);if(U!==void 0&&U>Date.now()){Ys(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${O}' (async mode)`);let $=Math.round((U-Date.now())/1e3);return i(p,$)}return e.addResponseSendingHook(async $=>k??$),n},"AsyncRateLimitInboundPolicy");var ta=(0,na.debug)("zuplo:policies:RateLimitInboundPolicy"),Qc="strict",ra=s(async(n,e,t,r)=>{if(g("policy.inbound.rate-limit"),(t.mode??Qc)==="async")return ea(n,e,t,r);let i=Date.now(),a=X.getLogger(e),u=s((l,d)=>{if(t.throwOnFailure)throw new W(l,{cause:d});a.error(l,d)},"throwOrLog"),c=s((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[ft]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d=await mt(r,t)(n,e,r),p=d.key,f=d.requestsAllowed??t.requestsAllowed,h=d.timeWindowMinutes??t.timeWindowMinutes,O=t.headerMode??"retry-after",P=gt(r,a),H=`rate-limit${y.instance.isTestMode||y.instance.isWorkingCopy?y.instance.build.BUILD_ID:""}/${r}/${p}`,k=await An(H,h,P,e.requestId);return k.count>f?(ta(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${H}' (strict mode)`),c(O,k.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-i;ta(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var qo;function oa(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(oa,"headersToNameValuePairs");function el(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(el,"queryToNameValueParis");function tl(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(tl,"parseIntOrUndefined");var ia={};async function nl(n,e,t,r){g("policy.inbound.readme-metrics");let o=new Date,i=Date.now();return qo||(qo={name:"zuplo",version:y.instance.build.ZUPLO_VERSION,comment:`zuplo/${y.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?Xe(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?Xe(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:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:qo,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:oa(n.headers),queryString:el(n.query)},response:{status:a.status,statusText:a.statusText,headers:oa(a.headers),content:{size:tl(n.headers.get("content-length"))}}}]}}},d=ia[t.apiKey];if(!d){let p=t.apiKey;d=new J("readme-metering-inbound-policy",10,async f=>{try{let h=t.url??"https://metrics.readme.io/request",O=await F.fetch(h,{method:"POST",body:JSON.stringify(f),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});O.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${O.status}: '${await O.text()}'`)}catch(h){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${h.message}'`),h}}),ia[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}s(nl,"ReadmeMetricsInboundPolicy");var rl=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 m(`RemoveHeadersInboundPolicy '${r}' options.headers must be a non-empty string array of header names`);let i=new Headers(n.headers);return o.forEach(u=>{i.delete(u)}),new te(n,{headers:i})},"RemoveHeadersInboundPolicy");var ol=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 m(`RemoveHeadersOutboundPolicy '${o}' options.headers must be a non-empty string array of header names`);let a=new Headers(n.headers);return i.forEach(c=>{a.delete(c)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"RemoveHeadersOutboundPolicy");var il=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 m(`RemoveQueryParamsInboundPolicy '${r}' options.params must be a non-empty string array of header names`);let i=new URL(n.url);return o.forEach(u=>{i.searchParams.delete(u)}),new te(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var sl=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 sa=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),al=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?sa():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?sa():n},"RequestSizeLimitInboundPolicy");var Rt=s(n=>{let e=n.route.raw();return e.parameters?e.parameters.map(r=>({name:r.name,location:r.in,required:r.required,deprecated:r.deprecated,allowEmptyValue:r.allowEmptyValue})):[]},"getParametersForOperation"),Pt=s((n,e,t,r,o)=>{let i=[],a=!0,u=[];return n.forEach(c=>{let l=c.required||o==="path";if(l&&!e[c.name])a=!1,i.push(`Required ${o} parameter '${c.name}' not found`);else if(!(!l&&!e[c.name])){let d=Hn(t,r,o,c.name),p=fe.instance.schemaValidator[d],f=p(e[c.name]),h=Uo(p.errors);f||(a=!1,u.push(`${o} parameter: ${c.name} : ${e[c.name]}`),i.push(`Invalid value for ${o} parameter: '${c.name}' ${h.join(", ")}`))}}),{isValid:a,invalidValues:u,errors:i}},"validateParameters"),Ce=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),Oe=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ae=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Uo=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 aa(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(h){let O=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,P=x.badRequest(e,n,{detail:`${O}, see errors property for more details`,errors:`${h}`});if(Oe(t.validateBody)&&Ce(n,t.logLevel??"info",O,[r],h),Ae(t.validateBody))return P}if(!e.headers.get("Content-Type")){let h=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,O=x.badRequest(e,n,{detail:h});return Oe(t.validateBody)&&Ce(n,t.logLevel??"info",h,[r],[h]),Ae(t.validateBody)?O:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=qn(n.route.path,e.method,o),u=fe.instance.schemaValidator[a];if(!u){let h=`No schema defined for method: ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,O=x.badRequest(e,n,{detail:h});return Oe(t.validateBody)&&Ce(n,t.logLevel??"info",h,[r],[h]),Ae(t.validateBody)?O:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Uo(l),f=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Oe(t.validateBody)&&Ce(n,t.logLevel??"info",d,[r],p),Ae(t.validateBody))return f}s(aa,"handleBodyValidation");function ua(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=Rt(n),i=Pt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=x.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Oe(t.validateHeaders)&&Ce(n,t.logLevel??"info",a,i.invalidValues,i.errors),Ae(t.validateHeaders))return u}}s(ua,"handleHeadersValidation");function ca(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=Rt(n),o=Pt(r.filter(i=>i.location==="path"),e.params,n.route.path,e.method.toLowerCase(),"path");if(!o.isValid){let i="Path parameters validation failed",a=x.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Oe(t.validatePathParameters)&&Ce(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ae(t.validatePathParameters))return a}}s(ca,"handlePathParameterValidation");function la(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=Rt(n),o=Pt(r.filter(i=>i.location==="query"),e.query,n.route.path,e.method.toLowerCase(),"query");if(!o.isValid){let i="Query parameters validation failed",a=x.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Oe(t.validateQueryParameters)&&Ce(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ae(t.validateQueryParameters))return a}}s(la,"handleQueryParameterValidation");var da=s(async(n,e,t)=>{g("policy.inbound.request-validation");let r=la(e,n,t);if(r!==void 0||(r=ca(e,n,t),r!==void 0)||(r=ua(e,n,t),r!==void 0))return r;let o=await aa(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),ul=da;var cl=s(async(n,e,t,r)=>{if(g("policy.inbound.require-origin"),t.origins===void 0||t.origins.length===0)throw new m(`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 x.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var ll=s(async(n,e,t)=>(g("policy.inbound.set-body"),new te(n,{body:t.body})),"SetBodyInboundPolicy");var dl=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 m(`SetHeadersInboundPolicy '${r}' options.headers must be a valid array of { name, value }`);let i=new Headers(n.headers);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetHeadersInboundPolicy '${r}' each option.headers[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.has(u.name)||c)&&i.set(u.name,u.value)}),new te(n,{headers:i})},"SetHeadersInboundPolicy");var pl=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 m(`SetHeadersOutboundPolicy '${o}' options.headers must be a valid array of { name, value }`);let a=new Headers(n.headers);return i.forEach(c=>{if(!c.name||c.name.length===0)throw new m(`SetHeadersOutboundPolicy '${o}' each option.headers[] entry must have a name property`);let l=c.overwrite===void 0?!0:c.overwrite;(!a.has(c.name)||l)&&a.set(c.name,c.value)}),new Response(n.body,{headers:a,status:n.status,statusText:n.statusText})},"SetHeadersOutboundPolicy");var ml=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 m(`SetQueryParamsInboundPolicy '${r}' options.params must be a valid array of { name, value }`);let i=new URL(n.url);return o.forEach(u=>{if(!u.name||u.name.length===0)throw new m(`SetQueryParamsInboundPolicy '${r}' each option.params[] entry must have a name property`);let c=u.overwrite===void 0?!0:u.overwrite;(!i.searchParams.has(u.name)||c)&&i.searchParams.set(u.name,u.value)}),new te(i.toString(),n)},"SetQueryParamsInboundPolicy");var gl=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 Error(`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 fl=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),hl=s(async(n,e,t,r)=>{if(g("policy.inbound.sleep"),!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await fl(t.sleepInMs),n},"SleepInboundPolicy");var yl=s(async(n,e,t,r)=>{g("policy.inbound.supabase-jwt-auth"),Y(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await be(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof te))throw new W("Invalid State - SupabaseJwtInboundPolicy encountered a non-response that wasn't a ZuploRequest type')");let a=t.requiredClaims;if(!a)return i;let u=n.user?.data.app_metadata;if(!u)throw new _(`SupabaseJwtInboundPolicy policy '${r}' - has requiredClaims but the JWT token had no app_metadata property`);let c=Object.keys(a),l=[];return c.forEach(d=>{let p=a[d];Array.isArray(p)?p.includes(u[d])||l.push(d):p!==u[d]&&l.push(d)}),l.length>0?x.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var bl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-azure-ad-service-auth"),Y(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await ce(r,void 0,t),i=new ie(o,e),a=await i.get(r);if(!a){let u=await wl(t,e);i.put(r,u.access_token,u.expires_in-(t.expirationOffsetSeconds??300)),a=u.access_token}return n.headers.set("Authorization",`Bearer ${a}`),n},"UpstreamAzureAdServiceAuthInboundPolicy");async function wl(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await ge({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 _("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 _("Response returned from Azure AD is not in the expected format.")}s(wl,"getAccessToken");var pa="https://accounts.google.com/o/oauth2/token",Zo,Rl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-firebase-admin-auth"),Y(t,r).required("serviceAccountJson","string"),Zo||(Zo=await Ee.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 ce(r,void 0,t),a=new ie(i,e),u=await a.get(r);if(!u){let c=await ke({serviceAccount:Zo,audience:pa,payload:o}),l=await un(pa,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new _("Invalid OAuth response from Firebase");u=l.access_token,a.put(r,u,(l.expires_in??3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamFirebaseAdminAuthInboundPolicy");var Pl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",Il=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Fo,El=s(async(n,e,t,r)=>{if(g("policy.inbound.upstream-firebase-user-auth"),Y(t,r).required("serviceAccountJson","string").required("webApiKey","string").optional("developerClaims","object").optional("userId","string").optional("userIdPropertyPath","string"),!t.userId&&!t.userIdPropertyPath)throw new m(`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(Il.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Fo||(Fo=await Ee.init(t.serviceAccountJson));let i=t.userId;if(!i&&!t.userIdPropertyPath){if(!n.user)throw new _("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 _(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Xe(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new _(`Unable to determine user from for the policy ${r}`);let a=await ce(r,void 0,t),u=new ie(a,e),c={uid:i,claims:o},l=await In(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ke({serviceAccount:Fo,audience:Pl,payload:c}),f=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,h=await Yi(f,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!h.idToken)throw new _("Invalid token response from Firebase");d=h.idToken,u.put(l,d,(h.expiresIn?parseInt(h.expiresIn):3600)-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${d}`),n},"UpstreamFirebaseUserAuthInboundPolicy");var $o,xl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-jwt"),Y(t,r).required("audience","string").required("serviceAccountJson","string"),$o||($o=await Ee.init(t.serviceAccountJson));let o=await ke({serviceAccount:$o,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var ma="https://www.googleapis.com/oauth2/v4/token",jo,Tl=s(async(n,e,t,r)=>{g("policy.inbound.upstream-gcp-service-auth"),Y(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),jo||(jo=await Ee.init(t.serviceAccountJson));let o={};if(t.scopes&&t.audience)throw new m("UpstreamGcpServiceAuthInboundPolicy - Either the 'scopes' or the 'audience' property can be set, not both.");if(t.scopes)try{let c=Ye(t.scopes);o.scope=c.join(" ")}catch(c){throw c instanceof m?new m(`UpstreamGcpServiceAuthInboundPolicy - The property 'scopes' is invalid. ${c.message}`):c}t.audience&&(o.target_audience=`${t.audience}`);let i=await ce(r,void 0,t),a;t.useMemoryCacheOnly?a=new nt(i):a=new ie(i,e);let u=await a.get(r);if(!u){let c=await ke({serviceAccount:jo,audience:ma,payload:o}),l=await un(ma,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new _("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new _("Invalid token response from GCP");u=l.access_token}a.put(r,u,3600-(t.expirationOffsetSeconds??300))}return n.headers.set("Authorization",`Bearer ${u}`),n},"UpstreamGcpServiceAuthInboundPolicy");var vl=s(async(n,e,t)=>{g("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return x.badRequest(n,e,{detail:"Invalid JSON body - expected well-formed JSON document"})}if(t.validator(o))return n;let{errors:a}=t.validator;if(!a)throw new W("Invalid state - validator error object is undefined even though validation failed.");let u=a.map(c=>c.instancePath===void 0||c.instancePath===""?"Body "+c.message:c.instancePath.replace("/","")+" "+c.message);return x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ga=s(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=s((P,S)=>e(P,"name",{value:S,configurable:!0}),"__name"),o=s((P,S)=>s(function(){return S||(0,P[t(P)[0]])((S={exports:{}}).exports,S),S.exports},"__require"),"__commonJS"),i=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(P){var S={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:function(k,j){return j},attributeValueProcessor:function(k,j){return j},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(k,j,U){return k}},H=r(function(k){return Object.assign({},S,k)},"buildOptions");P.buildOptions=H,P.defaultOptions=S}}),a=o({"node_modules/fast-xml-parser/src/util.js"(P){"use strict";var S=":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",H=S+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",k="["+S+"]["+H+"]*",j=new RegExp("^"+k+"$"),U=r(function(E,M){let V=[],G=M.exec(E);for(;G;){let v=[];v.startIndex=M.lastIndex-G[0].length;let T=G.length;for(let q=0;q<T;q++)v.push(G[q]);V.push(v),G=M.exec(E)}return V},"getAllMatches"),$=r(function(E){let M=j.exec(E);return!(M===null||typeof M>"u")},"isName");P.isExist=function(E){return typeof E<"u"},P.isEmptyObject=function(E){return Object.keys(E).length===0},P.merge=function(E,M,V){if(M){let G=Object.keys(M),v=G.length;for(let T=0;T<v;T++)V==="strict"?E[G[T]]=[M[G[T]]]:E[G[T]]=M[G[T]]}},P.getValue=function(E){return P.isExist(E)?E:""},P.isName=$,P.getAllMatches=U,P.nameRegexp=k}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(P,S){"use strict";var H=class{static{s(this,"XmlNode")}static{r(this,"XmlNode")}constructor(k){this.tagname=k,this.child=[],this[":@"]={}}add(k,j){k==="__proto__"&&(k="#__proto__"),this.child.push({[k]:j})}addChild(k){k.tagname==="__proto__"&&(k.tagname="#__proto__"),k[":@"]&&Object.keys(k[":@"]).length>0?this.child.push({[k.tagname]:k.child,":@":k[":@"]}):this.child.push({[k.tagname]:k.child})}};S.exports=H}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,S){var H=a();function k(v,T){let q={};if(v[T+3]==="O"&&v[T+4]==="C"&&v[T+5]==="T"&&v[T+6]==="Y"&&v[T+7]==="P"&&v[T+8]==="E"){T=T+9;let ae=1,K=!1,Q=!1,Te="";for(;T<v.length;T++)if(v[T]==="<"&&!Q){if(K&&$(v,T))T+=7,[entityName,val,T]=j(v,T+1),val.indexOf("&")===-1&&(q[G(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(K&&E(v,T))T+=8;else if(K&&M(v,T))T+=8;else if(K&&V(v,T))T+=9;else if(U)Q=!0;else throw new Error("Invalid DOCTYPE");ae++,Te=""}else if(v[T]===">"){if(Q?v[T-1]==="-"&&v[T-2]==="-"&&(Q=!1,ae--):ae--,ae===0)break}else v[T]==="["?K=!0:Te+=v[T];if(ae!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:q,i:T}}s(k,"readDocType"),r(k,"readDocType");function j(v,T){let q="";for(;T<v.length&&v[T]!=="'"&&v[T]!=='"';T++)q+=v[T];if(q=q.trim(),q.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ae=v[T++],K="";for(;T<v.length&&v[T]!==ae;T++)K+=v[T];return[q,K,T]}s(j,"readEntityExp"),r(j,"readEntityExp");function U(v,T){return v[T+1]==="!"&&v[T+2]==="-"&&v[T+3]==="-"}s(U,"isComment"),r(U,"isComment");function $(v,T){return v[T+1]==="!"&&v[T+2]==="E"&&v[T+3]==="N"&&v[T+4]==="T"&&v[T+5]==="I"&&v[T+6]==="T"&&v[T+7]==="Y"}s($,"isEntity"),r($,"isEntity");function E(v,T){return v[T+1]==="!"&&v[T+2]==="E"&&v[T+3]==="L"&&v[T+4]==="E"&&v[T+5]==="M"&&v[T+6]==="E"&&v[T+7]==="N"&&v[T+8]==="T"}s(E,"isElement"),r(E,"isElement");function M(v,T){return v[T+1]==="!"&&v[T+2]==="A"&&v[T+3]==="T"&&v[T+4]==="T"&&v[T+5]==="L"&&v[T+6]==="I"&&v[T+7]==="S"&&v[T+8]==="T"}s(M,"isAttlist"),r(M,"isAttlist");function V(v,T){return v[T+1]==="!"&&v[T+2]==="N"&&v[T+3]==="O"&&v[T+4]==="T"&&v[T+5]==="A"&&v[T+6]==="T"&&v[T+7]==="I"&&v[T+8]==="O"&&v[T+9]==="N"}s(V,"isNotation"),r(V,"isNotation");function G(v){if(H.isName(v))return v;throw new Error(`Invalid entity name ${v}`)}s(G,"validateEntityName"),r(G,"validateEntityName"),S.exports=k}}),l=o({"../../node_modules/strnum/strnum.js"(P,S){var H=/^[-+]?0x[a-fA-F0-9]+$/,k=/^([\-\+])?(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 j={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function U(E,M={}){if(M=Object.assign({},j,M),!E||typeof E!="string")return E;let V=E.trim();if(M.skipLike!==void 0&&M.skipLike.test(V))return E;if(M.hex&&H.test(V))return Number.parseInt(V,16);{let G=k.exec(V);if(G){let v=G[1],T=G[2],q=$(G[3]),ae=G[4]||G[6];if(!M.leadingZeros&&T.length>0&&v&&V[2]!==".")return E;if(!M.leadingZeros&&T.length>0&&!v&&V[1]!==".")return E;{let K=Number(V),Q=""+K;return Q.search(/[eE]/)!==-1||ae?M.eNotation?K:E:V.indexOf(".")!==-1?Q==="0"&&q===""||Q===q||v&&Q==="-"+q?K:E:T?q===Q||v+q===Q?K:E:V===Q||V===v+Q?K:E}}else return E}}s(U,"toNumber"),r(U,"toNumber");function $(E){return E&&E.indexOf(".")!==-1&&(E=E.replace(/0+$/,""),E==="."?E="0":E[0]==="."?E="0"+E:E[E.length-1]==="."&&(E=E.substr(0,E.length-1))),E}s($,"trimZeros"),r($,"trimZeros"),S.exports=U}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,S){"use strict";var H=a(),k=u(),j=c(),U=l(),$=class{static{s(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(R){this.options=R,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:(I,A)=>String.fromCharCode(Number.parseInt(A,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(I,A)=>String.fromCharCode(Number.parseInt(A,16))}},this.addExternalEntities=E,this.parseXml=T,this.parseTextData=M,this.resolveNameSpace=V,this.buildAttributesMap=v,this.isItStopNode=Q,this.replaceEntitiesValue=ae,this.readStopNodeData=B,this.saveTextToParentTag=K,this.addChild=q}};function E(R){let I=Object.keys(R);for(let A=0;A<I.length;A++){let z=I[A];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:R[z]}}}s(E,"addExternalEntities"),r(E,"addExternalEntities");function M(R,I,A,z,L,N,ee){if(R!==void 0&&(this.options.trimValues&&!z&&(R=R.trim()),R.length>0)){ee||(R=this.replaceEntitiesValue(R));let Z=this.options.tagValueProcessor(I,R,A,L,N);return Z==null?R:typeof Z!=typeof R||Z!==R?Z:this.options.trimValues?ue(R,this.options.parseTagValue,this.options.numberParseOptions):R.trim()===R?ue(R,this.options.parseTagValue,this.options.numberParseOptions):R}}s(M,"parseTextData"),r(M,"parseTextData");function V(R){if(this.options.removeNSPrefix){let I=R.split(":"),A=R.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(R=A+I[1])}return R}s(V,"resolveNameSpace"),r(V,"resolveNameSpace");var G=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function v(R,I,A){if(!this.options.ignoreAttributes&&typeof R=="string"){let z=H.getAllMatches(R,G),L=z.length,N={};for(let ee=0;ee<L;ee++){let Z=this.resolveNameSpace(z[ee][1]),D=z[ee][4],oe=this.options.attributeNamePrefix+Z;if(Z.length)if(this.options.transformAttributeName&&(oe=this.options.transformAttributeName(oe)),oe==="__proto__"&&(oe="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let ne=this.options.attributeValueProcessor(Z,D,I);ne==null?N[oe]=D:typeof ne!=typeof D||ne!==D?N[oe]=ne:N[oe]=ue(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(N[oe]=!0)}if(!Object.keys(N).length)return;if(this.options.attributesGroupName){let ee={};return ee[this.options.attributesGroupName]=N,ee}return N}}s(v,"buildAttributesMap"),r(v,"buildAttributesMap");var T=r(function(R){R=R.replace(/\r\n?/g,`
62
+ `);let I=new k("!xml"),A=I,z="",L="";for(let N=0;N<R.length;N++)if(R[N]==="<")if(R[N+1]==="/"){let Z=b(R,">",N,"Closing Tag is not closed."),D=R.substring(N+2,Z).trim();if(this.options.removeNSPrefix){let Se=D.indexOf(":");Se!==-1&&(D=D.substr(Se+1))}this.options.transformTagName&&(D=this.options.transformTagName(D)),A&&(z=this.saveTextToParentTag(z,A,L));let oe=L.substring(L.lastIndexOf(".")+1);if(D&&this.options.unpairedTags.indexOf(D)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${D}>`);let ne=0;oe&&this.options.unpairedTags.indexOf(oe)!==-1?(ne=L.lastIndexOf(".",L.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ne=L.lastIndexOf("."),L=L.substring(0,ne),A=this.tagsNodeStack.pop(),z="",N=Z}else if(R[N+1]==="?"){let Z=C(R,N,!1,"?>");if(!Z)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,A,L),!(this.options.ignoreDeclaration&&Z.tagName==="?xml"||this.options.ignorePiTags)){let D=new k(Z.tagName);D.add(this.options.textNodeName,""),Z.tagName!==Z.tagExp&&Z.attrExpPresent&&(D[":@"]=this.buildAttributesMap(Z.tagExp,L,Z.tagName)),this.addChild(A,D,L)}N=Z.closeIndex+1}else if(R.substr(N+1,3)==="!--"){let Z=b(R,"-->",N+4,"Comment is not closed.");if(this.options.commentPropName){let D=R.substring(N+4,Z-2);z=this.saveTextToParentTag(z,A,L),A.add(this.options.commentPropName,[{[this.options.textNodeName]:D}])}N=Z}else if(R.substr(N+1,2)==="!D"){let Z=j(R,N);this.docTypeEntities=Z.entities,N=Z.i}else if(R.substr(N+1,2)==="!["){let Z=b(R,"]]>",N,"CDATA is not closed.")-2,D=R.substring(N+9,Z);z=this.saveTextToParentTag(z,A,L);let oe=this.parseTextData(D,A.tagname,L,!0,!1,!0,!0);oe==null&&(oe=""),this.options.cdataPropName?A.add(this.options.cdataPropName,[{[this.options.textNodeName]:D}]):A.add(this.options.textNodeName,oe),N=Z+2}else{let Z=C(R,N,this.options.removeNSPrefix),D=Z.tagName,oe=Z.rawTagName,ne=Z.tagExp,Se=Z.attrExpPresent,Xo=Z.closeIndex;this.options.transformTagName&&(D=this.options.transformTagName(D)),A&&z&&A.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,A,L,!1));let Yo=A;if(Yo&&this.options.unpairedTags.indexOf(Yo.tagname)!==-1&&(A=this.tagsNodeStack.pop(),L=L.substring(0,L.lastIndexOf("."))),D!==I.tagname&&(L+=L?"."+D:D),this.isItStopNode(this.options.stopNodes,L,D)){let ve="";if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1)N=Z.closeIndex;else if(this.options.unpairedTags.indexOf(D)!==-1)N=Z.closeIndex;else{let Mn=this.readStopNodeData(R,oe,Xo+1);if(!Mn)throw new Error(`Unexpected end of ${oe}`);N=Mn.i,ve=Mn.tagContent}let Dn=new k(D);D!==ne&&Se&&(Dn[":@"]=this.buildAttributesMap(ne,L,D)),ve&&(ve=this.parseTextData(ve,D,L,!0,Se,!0,!0)),L=L.substr(0,L.lastIndexOf(".")),Dn.add(this.options.textNodeName,ve),this.addChild(A,Dn,L)}else{if(ne.length>0&&ne.lastIndexOf("/")===ne.length-1){D[D.length-1]==="/"?(D=D.substr(0,D.length-1),L=L.substr(0,L.length-1),ne=D):ne=ne.substr(0,ne.length-1),this.options.transformTagName&&(D=this.options.transformTagName(D));let ve=new k(D);D!==ne&&Se&&(ve[":@"]=this.buildAttributesMap(ne,L,D)),this.addChild(A,ve,L),L=L.substr(0,L.lastIndexOf("."))}else{let ve=new k(D);this.tagsNodeStack.push(A),D!==ne&&Se&&(ve[":@"]=this.buildAttributesMap(ne,L,D)),this.addChild(A,ve,L),A=ve}z="",N=Xo}}else z+=R[N];return I.child},"parseXml");function q(R,I,A){let z=this.options.updateTag(I.tagname,A,I[":@"]);z===!1||(typeof z=="string"&&(I.tagname=z),R.addChild(I))}s(q,"addChild"),r(q,"addChild");var ae=r(function(R){if(this.options.processEntities){for(let I in this.docTypeEntities){let A=this.docTypeEntities[I];R=R.replace(A.regx,A.val)}for(let I in this.lastEntities){let A=this.lastEntities[I];R=R.replace(A.regex,A.val)}if(this.options.htmlEntities)for(let I in this.htmlEntities){let A=this.htmlEntities[I];R=R.replace(A.regex,A.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function K(R,I,A,z){return R&&(z===void 0&&(z=Object.keys(I.child).length===0),R=this.parseTextData(R,I.tagname,A,!1,I[":@"]?Object.keys(I[":@"]).length!==0:!1,z),R!==void 0&&R!==""&&I.add(this.options.textNodeName,R),R=""),R}s(K,"saveTextToParentTag"),r(K,"saveTextToParentTag");function Q(R,I,A){let z="*."+A;for(let L in R){let N=R[L];if(z===N||I===N)return!0}return!1}s(Q,"isItStopNode"),r(Q,"isItStopNode");function Te(R,I,A=">"){let z,L="";for(let N=I;N<R.length;N++){let ee=R[N];if(z)ee===z&&(z="");else if(ee==='"'||ee==="'")z=ee;else if(ee===A[0])if(A[1]){if(R[N+1]===A[1])return{data:L,index:N}}else return{data:L,index:N};else ee===" "&&(ee=" ");L+=ee}}s(Te,"tagExpWithClosingIndex"),r(Te,"tagExpWithClosingIndex");function b(R,I,A,z){let L=R.indexOf(I,A);if(L===-1)throw new Error(z);return L+I.length-1}s(b,"findClosingIndex"),r(b,"findClosingIndex");function C(R,I,A,z=">"){let L=Te(R,I+1,z);if(!L)return;let N=L.data,ee=L.index,Z=N.search(/\s/),D=N,oe=!0;Z!==-1&&(D=N.substring(0,Z),N=N.substring(Z+1).trimStart());let ne=D;if(A){let Se=D.indexOf(":");Se!==-1&&(D=D.substr(Se+1),oe=D!==L.data.substr(Se+1))}return{tagName:D,tagExp:N,closeIndex:ee,attrExpPresent:oe,rawTagName:ne}}s(C,"readTagExp"),r(C,"readTagExp");function B(R,I,A){let z=A,L=1;for(;A<R.length;A++)if(R[A]==="<")if(R[A+1]==="/"){let N=b(R,">",A,`${I} is not closed`);if(R.substring(A+2,N).trim()===I&&(L--,L===0))return{tagContent:R.substring(z,A),i:N};A=N}else if(R[A+1]==="?")A=b(R,"?>",A+1,"StopNode is not closed.");else if(R.substr(A+1,3)==="!--")A=b(R,"-->",A+3,"StopNode is not closed.");else if(R.substr(A+1,2)==="![")A=b(R,"]]>",A,"StopNode is not closed.")-2;else{let N=C(R,A,">");N&&((N&&N.tagName)===I&&N.tagExp[N.tagExp.length-1]!=="/"&&L++,A=N.closeIndex)}}s(B,"readStopNodeData"),r(B,"readStopNodeData");function ue(R,I,A){if(I&&typeof R=="string"){let z=R.trim();return z==="true"?!0:z==="false"?!1:U(R,A)}else return H.isExist(R)?R:""}s(ue,"parseValue"),r(ue,"parseValue"),S.exports=$}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function S($,E){return H($,E)}s(S,"prettify"),r(S,"prettify");function H($,E,M){let V,G={};for(let v=0;v<$.length;v++){let T=$[v],q=k(T),ae="";if(M===void 0?ae=q:ae=M+"."+q,q===E.textNodeName)V===void 0?V=T[q]:V+=""+T[q];else{if(q===void 0)continue;if(T[q]){let K=H(T[q],E,ae),Q=U(K,E);T[":@"]?j(K,T[":@"],ae,E):Object.keys(K).length===1&&K[E.textNodeName]!==void 0&&!E.alwaysCreateTextNode?K=K[E.textNodeName]:Object.keys(K).length===0&&(E.alwaysCreateTextNode?K[E.textNodeName]="":K=""),G[q]!==void 0&&G.hasOwnProperty(q)?(Array.isArray(G[q])||(G[q]=[G[q]]),G[q].push(K)):E.isArray(q,ae,Q)?G[q]=[K]:G[q]=K}}}return typeof V=="string"?V.length>0&&(G[E.textNodeName]=V):V!==void 0&&(G[E.textNodeName]=V),G}s(H,"compress"),r(H,"compress");function k($){let E=Object.keys($);for(let M=0;M<E.length;M++){let V=E[M];if(V!==":@")return V}}s(k,"propName"),r(k,"propName");function j($,E,M,V){if(E){let G=Object.keys(E),v=G.length;for(let T=0;T<v;T++){let q=G[T];V.isArray(q,M+"."+q,!0,!0)?$[q]=[E[q]]:$[q]=E[q]}}}s(j,"assignAttributes"),r(j,"assignAttributes");function U($,E){let{textNodeName:M}=E,V=Object.keys($).length;return!!(V===0||V===1&&($[M]||typeof $[M]=="boolean"||$[M]===0))}s(U,"isLeafTag"),r(U,"isLeafTag"),P.prettify=S}}),f=o({"node_modules/fast-xml-parser/src/validator.js"(P){"use strict";var S=a(),H={allowBooleanAttributes:!1,unpairedTags:[]};P.validate=function(b,C){C=Object.assign({},H,C);let B=[],ue=!1,R=!1;b[0]==="\uFEFF"&&(b=b.substr(1));for(let I=0;I<b.length;I++)if(b[I]==="<"&&b[I+1]==="?"){if(I+=2,I=j(b,I),I.err)return I}else if(b[I]==="<"){let A=I;if(I++,b[I]==="!"){I=U(b,I);continue}else{let z=!1;b[I]==="/"&&(z=!0,I++);let L="";for(;I<b.length&&b[I]!==">"&&b[I]!==" "&&b[I]!==" "&&b[I]!==`
63
+ `&&b[I]!=="\r";I++)L+=b[I];if(L=L.trim(),L[L.length-1]==="/"&&(L=L.substring(0,L.length-1),I--),!K(L)){let Z;return L.trim().length===0?Z="Invalid space after '<'.":Z="Tag '"+L+"' is an invalid name.",q("InvalidTag",Z,Q(b,I))}let N=M(b,I);if(N===!1)return q("InvalidAttr","Attributes for '"+L+"' have open quote.",Q(b,I));let ee=N.value;if(I=N.index,ee[ee.length-1]==="/"){let Z=I-ee.length;ee=ee.substring(0,ee.length-1);let D=G(ee,C);if(D===!0)ue=!0;else return q(D.err.code,D.err.msg,Q(b,Z+D.err.line))}else if(z)if(N.tagClosed){if(ee.trim().length>0)return q("InvalidTag","Closing tag '"+L+"' can't have attributes or invalid starting.",Q(b,A));{let Z=B.pop();if(L!==Z.tagName){let D=Q(b,Z.tagStartPos);return q("InvalidTag","Expected closing tag '"+Z.tagName+"' (opened in line "+D.line+", col "+D.col+") instead of closing tag '"+L+"'.",Q(b,A))}B.length==0&&(R=!0)}}else return q("InvalidTag","Closing tag '"+L+"' doesn't have proper closing.",Q(b,I));else{let Z=G(ee,C);if(Z!==!0)return q(Z.err.code,Z.err.msg,Q(b,I-ee.length+Z.err.line));if(R===!0)return q("InvalidXml","Multiple possible root nodes found.",Q(b,I));C.unpairedTags.indexOf(L)!==-1||B.push({tagName:L,tagStartPos:A}),ue=!0}for(I++;I<b.length;I++)if(b[I]==="<")if(b[I+1]==="!"){I++,I=U(b,I);continue}else if(b[I+1]==="?"){if(I=j(b,++I),I.err)return I}else break;else if(b[I]==="&"){let Z=T(b,I);if(Z==-1)return q("InvalidChar","char '&' is not expected.",Q(b,I));I=Z}else if(R===!0&&!k(b[I]))return q("InvalidXml","Extra text at the end",Q(b,I));b[I]==="<"&&I--}}else{if(k(b[I]))continue;return q("InvalidChar","char '"+b[I]+"' is not expected.",Q(b,I))}if(ue){if(B.length==1)return q("InvalidTag","Unclosed tag '"+B[0].tagName+"'.",Q(b,B[0].tagStartPos));if(B.length>0)return q("InvalidXml","Invalid '"+JSON.stringify(B.map(I=>I.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return q("InvalidXml","Start tag expected.",1);return!0};function k(b){return b===" "||b===" "||b===`
64
+ `||b==="\r"}s(k,"isWhiteSpace"),r(k,"isWhiteSpace");function j(b,C){let B=C;for(;C<b.length;C++)if(b[C]=="?"||b[C]==" "){let ue=b.substr(B,C-B);if(C>5&&ue==="xml")return q("InvalidXml","XML declaration allowed only at the start of the document.",Q(b,C));if(b[C]=="?"&&b[C+1]==">"){C++;break}else continue}return C}s(j,"readPI"),r(j,"readPI");function U(b,C){if(b.length>C+5&&b[C+1]==="-"&&b[C+2]==="-"){for(C+=3;C<b.length;C++)if(b[C]==="-"&&b[C+1]==="-"&&b[C+2]===">"){C+=2;break}}else if(b.length>C+8&&b[C+1]==="D"&&b[C+2]==="O"&&b[C+3]==="C"&&b[C+4]==="T"&&b[C+5]==="Y"&&b[C+6]==="P"&&b[C+7]==="E"){let B=1;for(C+=8;C<b.length;C++)if(b[C]==="<")B++;else if(b[C]===">"&&(B--,B===0))break}else if(b.length>C+9&&b[C+1]==="["&&b[C+2]==="C"&&b[C+3]==="D"&&b[C+4]==="A"&&b[C+5]==="T"&&b[C+6]==="A"&&b[C+7]==="["){for(C+=8;C<b.length;C++)if(b[C]==="]"&&b[C+1]==="]"&&b[C+2]===">"){C+=2;break}}return C}s(U,"readCommentAndCDATA"),r(U,"readCommentAndCDATA");var $='"',E="'";function M(b,C){let B="",ue="",R=!1;for(;C<b.length;C++){if(b[C]===$||b[C]===E)ue===""?ue=b[C]:ue!==b[C]||(ue="");else if(b[C]===">"&&ue===""){R=!0;break}B+=b[C]}return ue!==""?!1:{value:B,index:C,tagClosed:R}}s(M,"readAttributeStr"),r(M,"readAttributeStr");var V=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function G(b,C){let B=S.getAllMatches(b,V),ue={};for(let R=0;R<B.length;R++){if(B[R][1].length===0)return q("InvalidAttr","Attribute '"+B[R][2]+"' has no space in starting.",Te(B[R]));if(B[R][3]!==void 0&&B[R][4]===void 0)return q("InvalidAttr","Attribute '"+B[R][2]+"' is without value.",Te(B[R]));if(B[R][3]===void 0&&!C.allowBooleanAttributes)return q("InvalidAttr","boolean attribute '"+B[R][2]+"' is not allowed.",Te(B[R]));let I=B[R][2];if(!ae(I))return q("InvalidAttr","Attribute '"+I+"' is an invalid name.",Te(B[R]));if(!ue.hasOwnProperty(I))ue[I]=1;else return q("InvalidAttr","Attribute '"+I+"' is repeated.",Te(B[R]))}return!0}s(G,"validateAttributeString"),r(G,"validateAttributeString");function v(b,C){let B=/\d/;for(b[C]==="x"&&(C++,B=/[\da-fA-F]/);C<b.length;C++){if(b[C]===";")return C;if(!b[C].match(B))break}return-1}s(v,"validateNumberAmpersand"),r(v,"validateNumberAmpersand");function T(b,C){if(C++,b[C]===";")return-1;if(b[C]==="#")return C++,v(b,C);let B=0;for(;C<b.length;C++,B++)if(!(b[C].match(/\w/)&&B<20)){if(b[C]===";")break;return-1}return C}s(T,"validateAmpersand"),r(T,"validateAmpersand");function q(b,C,B){return{err:{code:b,msg:C,line:B.line||B,col:B.col}}}s(q,"getErrorObject"),r(q,"getErrorObject");function ae(b){return S.isName(b)}s(ae,"validateAttrName"),r(ae,"validateAttrName");function K(b){return S.isName(b)}s(K,"validateTagName"),r(K,"validateTagName");function Q(b,C){let B=b.substring(0,C).split(/\r?\n/);return{line:B.length,col:B[B.length-1].length+1}}s(Q,"getLineNumberForPosition"),r(Q,"getLineNumberForPosition");function Te(b){return b.startIndex+b[1].length}s(Te,"getPositionFromMatch"),r(Te,"getPositionFromMatch")}}),h=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,S){var{buildOptions:H}=i(),k=d(),{prettify:j}=p(),U=f(),$=class{static{s(this,"XMLParser")}static{r(this,"XMLParser")}constructor(E){this.externalEntities={},this.options=H(E)}parse(E,M){if(typeof E!="string")if(E.toString)E=E.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(M){M===!0&&(M={});let v=U.validate(E,M);if(v!==!0)throw Error(`${v.err.msg}:${v.err.line}:${v.err.col}`)}let V=new k(this.options);V.addExternalEntities(this.externalEntities);let G=V.parseXml(E);return this.options.preserveOrder||G===void 0?G:j(G,this.options)}addEntity(E,M){if(M.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(E.indexOf("&")!==-1||E.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(M==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[E]=M}};S.exports=$}});let O=h();return new O(n)},"getXmlParser");var zo=class extends Fe{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),g("policy.outbound.xml-to-json"),Y(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?it(e.parseOnStatusCodes):void 0,this.parser=ga({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 u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new _(c)}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 Bo=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new W(`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 Vo=class{static{s(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new Error("BackgroundDispatcher: options.msDelay is required");this.#e=new J(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),hn().waitUntil(this.#e.waitUntilFlushed())}};var fa=10,ha=3e4,Go=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=ha,this.#r=fa}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:ha,this.#r=fa}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await Sl(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#u(e);if(r)return r}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);hn().waitUntil(t)}}async#c(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 Error(`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 Sl(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new Error(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}s(Sl,"waitUntilTrue");var Wo=["sha-1","sha-256","sha-384","sha-512"],_n=class{static{s(this,"BaseCryptoBeta")}};var Ko=class extends _n{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(!Wo.includes(e.toLowerCase()))throw new _(`Algorithm ${e} is not supported. Try using ${Wo.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};var Nn=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var Jo=class extends Nn{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=y.instance.runtime.ZUPLO_KV;if(!t)throw new Qo("The Key Value Store feature is not enabled for this project.");this.#e=t,g("platform.kv-store")}put(e,t,r){if(typeof e!="string")throw new m("value must be of type string");return this.#e.put(e,t,r?{expirationTtl:r.expirationSecondsTtl}:void 0)}get(e,t){return this.#e.get(e,{type:"text",cacheTtl:t?.cacheSecondsTtl})}delete(e){return this.#e.delete(e)}};export{Qr as AWSLoggingPlugin,tc as AmberfloMeteringInboundPolicy,wo as AmberfloMeteringPolicy,oc as ApiAuthKeyInboundPolicy,Ro as ApiKeyInboundPolicy,co as AuditLogDataStaxProvider,lo as AuditLogPlugin,cc as Auth0JwtInboundPolicy,Pu as AwsLambdaHandlerExtensions,xo as AxiomaticsAuthZInboundPolicy,Vo as BackgroundDispatcher,Go as BackgroundLoader,lc as BasicAuthInboundPolicy,ra as BasicRateLimitInboundPolicy,J as BatchDispatch,So as BrownoutInboundPolicy,Pc as CachingInboundPolicy,Ic as ChangeMethodInboundPolicy,Ec as ClearHeadersInboundPolicy,xc as ClearHeadersOutboundPolicy,Tc as ClerkJwtInboundPolicy,vc as CognitoJwtInboundPolicy,Lo as ComplexRateLimitInboundPolicy,Nc as CompositeInboundPolicy,m as ConfigurationError,sr as ContentTypes,me as ContextData,Ko as CryptoBeta,Dc as CurityPhantomTokenInboundPolicy,Lr as DataDogLoggingPlugin,no as DataDogMetricsPlugin,zr as DynaTraceLoggingPlugin,so as DynatraceMetricsPlugin,Hc as FirebaseJwtInboundPolicy,qc as FormDataToJsonInboundPolicy,Uc as GeoFilterInboundPolicy,vr as GoogleCloudLoggingPlugin,Mr as Handler,x as HttpProblems,Yt as HttpStatusCode,de as InboundPolicy,Zc as JWTScopeValidationInboundPolicy,Jo as KeyValueStore,Vr as LokiLoggingPlugin,qt as LookupResult,ie as MemoryZoneReadThroughCache,Fc as MockApiInboundPolicy,Wc as MoesifInboundPolicy,Do as MonetizationInboundPolicy,Jc as OktaJwtInboundPolicy,Mo as OpenFGAAuthZInboundPolicy,be as OpenIdJwtInboundPolicy,Fe as OutboundPolicy,Ke as ProblemResponseFormatter,Yc as PropelAuthJwtInboundPolicy,ra as RateLimitInboundPolicy,nl as ReadmeMetricsInboundPolicy,rl as RemoveHeadersInboundPolicy,ol as RemoveHeadersOutboundPolicy,il as RemoveQueryParamsInboundPolicy,sl as ReplaceStringOutboundPolicy,al as RequestSizeLimitInboundPolicy,da as RequestValidationInboundPolicy,cl as RequireOriginInboundPolicy,St as ResponseSendingEvent,Ct as ResponseSentEvent,Ut as Router,_ as RuntimeError,Gt as SYSTEM_LOGGER,ul as SchemaBasedRequestValidation,Le as SemanticAttributes,Bo as ServiceProviderImpl,ll as SetBodyInboundPolicy,dl as SetHeadersInboundPolicy,pl as SetHeadersOutboundPolicy,ml as SetQueryParamsInboundPolicy,gl as SetStatusOutboundPolicy,hl as SleepInboundPolicy,Ss as StripeMonetizationPlugin,Ft as StripeWebhookVerificationInboundPolicy,Kr as SumoLogicLoggingPlugin,yl as SupabaseJwtInboundPolicy,qe as SystemRouteName,xt as TelemetryPlugin,bl as UpstreamAzureAdServiceAuthInboundPolicy,Rl as UpstreamFirebaseAdminAuthInboundPolicy,El as UpstreamFirebaseUserAuthInboundPolicy,xl as UpstreamGcpJwtInboundPolicy,Tl as UpstreamGcpServiceAuthInboundPolicy,Xr as VMWareLogInsightLoggingPlugin,vl as ValidateJsonSchemaInbound,zo as XmlToJsonOutboundPolicy,It as ZoneCache,te as ZuploRequest,Iu as awsLambdaHandler,we as environment,Hn as getIdForParameterSchema,ba as getIdForRefSchema,qn as getIdForRequestBodySchema,ya as getRawOperationDataIdentifierName,ur as httpStatuses,Au as openApiSpecHandler,ku as redirectHandler,wa as sanitizedIdentifierName,ar as serialize,Bc as setMoesifContext,g as trackFeature,Nu as urlForwardHandler,Mu as urlRewriteHandler,Hu as webSocketHandler,qu as webSocketPipelineHandler};
65
65
  /*! For license information please see index.js.LEGAL.txt */