@zuplo/runtime 5.2179.0 → 5.2180.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 He,d as fe,e as ta,f as Nn,g as Dn,h as na,i as ra}from"./chunk-QSL25HFO.js";import{a as et,b as K,c as k,d as m,e as Go,f as q,g as Wo}from"./chunk-CI735RIK.js";import{a as b}from"./chunk-HPMPWPKQ.js";import{a as s,c as Xe}from"./chunk-4DUPDUSC.js";Function.prototype.toString=function(){return"[native code]"};var Ut=globalThis,Ko=Ut.caches;if(Ko){let n=Ko.open;Ut.caches.open=function(e){let t=b.instance.deploymentName??b.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Ut.caches.default,Object.freeze(Ut.caches)}var Jo=new Map,Mn=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)})}},tt=class{static{s(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let r=Jo.get(e);r||(r=new Mn(t),Jo.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 Hn="__zuplo-expiry-header",yt=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(Hn);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(Hn,`${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(Hn,`${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 ae=class{static{s(this,"MemoryZoneReadThroughCache")}constructor(e,t){let r=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new tt(r),this.#n=new yt(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 Yo="zuplo-request-id",ze="zp-rid",Un="zp-body-removed",Be="cf-ray",Qo="x-real-ip",Zn="cf-ipcity",qn="cf-ipcontinent",$n="cf-ipcountry",Fn="cf-iplongitude",jn="cf-iplatitude",Xo="cf-region",ei="cf-region-code",ti="cf-metro-code",ni="cf-postal-code",ri="cf-timezone",oi="zp-ipcity",ii="zp-ipcontinent",si="zp-ipcountry",ai="zp-iplongitude",ui="zp-iplatitude",ci="true-client-ip",zn="zp-asn",Bn="zp-asorg",Vn="zp-colo",Gn="zp-postalcode",Wn="zp-metrocode",Kn="zp-region",Jn="zp-regioncode",Yn="zp-timezone",li=[Zn,qn,$n,Fn,jn,zn,Bn,Vn,Gn,Wn,Kn,Jn,Yn],di=["zp-","cf-"],pi=[ze,Be,Un];var bt="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",Zt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",qt="system-logger";var Ji=Xe(et());import{trace as $a}from"@opentelemetry/api";import{SpanStatusCode as oa,trace as ia}from"@opentelemetry/api";import{SpanStatusCode as tr,trace as nr}from"@opentelemetry/api";var mi=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function gi(n){mi=n}s(gi,"setTelemetryInitFunction");var fi=s(n=>mi(n),"proxyHandler");var Ue=class{static{s(this,"RuntimePlugin")}},Ne=class extends Ue{static{s(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},$t=class extends Ne{static{s(this,"MeteringPlugin")}},wt=class extends Ue{static{s(this,"TelemetryPlugin")}};var Rt=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&&(n.problemResponseFormat=(t,r,o)=>{try{return e(t,r,o)}catch(i){throw new k("Error in custom 'problemResponseFormat'",{cause:i})}})}},Ve=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Rt.problemResponseFormat(e,t,r)}};function Ft(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&Ft(t)}return Object.freeze(n)}s(Ft,"deepFreeze");var X=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 Ft(this.#e)}get params(){return Ft(this.#t)}user};var Pt={},De=[],Qn=[],Xn=[],er=[];var jt={addPlugin(n){De.push(n)},addRequestHook(n){Qn.push(n)},addResponseSendingHook(n){Xn.push(n)},addResponseSendingFinalHook(n){er.push(n)}},yi=s(async(n,e)=>{if(Qn.length===0)return n;let t=nr.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of Qn){let a=await t.startActiveSpan(i.name,async u=>{let c=await i(o,e);if(c instanceof X||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:tr.ERROR}),l}});if(a instanceof X)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),bi=s(async(n,e,t)=>{if(Xn.length===0)return n;let r=nr.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:tr.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),wi=s(async(n,e,t)=>{if(er.length===0)return;let r=nr.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of er)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:tr.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),hi=!1;async function Ri(n=()=>Promise.resolve()){if(!hi){await n(jt),Pt.value=jt;for(let e of De)if(e instanceof wt){let{requestHandlerProxy:t}=e.instrument({accountName:b.instance.build.ACCOUNT_NAME,projectName:b.instance.build.PROJECT_NAME,buildId:b.instance.build.BUILD_ID,zuploVersion:b.instance.build.ZUPLO_VERSION,compatibilityDate:b.instance.build.COMPATIBILITY_DATE,instanceId:b.instance.instanceId,environmentType:b.instance.loggingEnvironmentType,environmentStage:b.instance.loggingEnvironmentStage,deploymentName:b.instance.deploymentName});gi(t)}for(let e of De)e instanceof Ne&&await e.initialize(jt);Rt.setProblemResponseFormat(jt.problemResponseFormat),hi=!0}}s(Ri,"initializeRuntime");var rr={Json:"application/json",Form:"application/x-www-form-urlencoded"};function or(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(rr.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(rr.Json)||!e?JSON.stringify(n):n}s(or,"serialize");function nt(n){return de.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(de.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}s(nt,"isSystemRoute");var ue=class{static{s(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=(e,t)=>async(r,o)=>ia.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:oa.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 $=>{let U=await r($,i);return sa(U)},t)(P,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(nt(d)&&b.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new It(o,l);i.dispatchEvent(p);let g=pe.getContextExtensions(i),f=g.latestRequest,A;try{A=await p.mutableResponse}catch(P){return i.log.error(P),t.errorHandler(o,i,P)}try{A=await g.onResponseSending(A,f,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,i,P)}try{A=await bi(A,f,i)}catch(P){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(o,i,P)}i.dispatchEvent(new Et(o,A));try{await g.onResponseSendingFinal(l,f,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await wi(l,f,i)}catch(P){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return A}};function sa(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(or(n),{headers:{"content-type":"application/json"}})}s(sa,"resultToResponse");var zt=(y=>(y[y.CONTINUE=100]="CONTINUE",y[y.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",y[y.PROCESSING=102]="PROCESSING",y[y.EARLY_HINTS=103]="EARLY_HINTS",y[y.OK=200]="OK",y[y.CREATED=201]="CREATED",y[y.ACCEPTED=202]="ACCEPTED",y[y.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",y[y.NO_CONTENT=204]="NO_CONTENT",y[y.RESET_CONTENT=205]="RESET_CONTENT",y[y.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",y[y.MULTI_STATUS=207]="MULTI_STATUS",y[y.ALREADY_REPORTED=208]="ALREADY_REPORTED",y[y.IM_USED=226]="IM_USED",y[y.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",y[y.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",y[y.FOUND=302]="FOUND",y[y.SEE_OTHER=303]="SEE_OTHER",y[y.NOT_MODIFIED=304]="NOT_MODIFIED",y[y.USE_PROXY=305]="USE_PROXY",y[y.SWITCH_PROXY=306]="SWITCH_PROXY",y[y.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",y[y.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",y[y.BAD_REQUEST=400]="BAD_REQUEST",y[y.UNAUTHORIZED=401]="UNAUTHORIZED",y[y.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",y[y.FORBIDDEN=403]="FORBIDDEN",y[y.NOT_FOUND=404]="NOT_FOUND",y[y.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",y[y.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",y[y.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",y[y.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",y[y.CONFLICT=409]="CONFLICT",y[y.GONE=410]="GONE",y[y.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",y[y.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",y[y.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",y[y.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",y[y.URI_TOO_LONG=414]="URI_TOO_LONG",y[y.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",y[y.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",y[y.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",y[y.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",y[y.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",y[y.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",y[y.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",y[y.LOCKED=423]="LOCKED",y[y.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",y[y.TOO_EARLY=425]="TOO_EARLY",y[y.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",y[y.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",y[y.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",y[y.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",y[y.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",y[y.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",y[y.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",y[y.BAD_GATEWAY=502]="BAD_GATEWAY",y[y.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",y[y.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",y[y.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",y[y.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",y[y.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",y[y.LOOP_DETECTED=508]="LOOP_DETECTED",y[y.NOT_EXTENDED=510]="NOT_EXTENDED",y[y.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",y))(zt||{}),Pi={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 aa={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"},ir=aa;function ua(n){return`${new URL(n.url).pathname}`}s(ua,"instance");function ca(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:b.instance.build.BUILD_ID},r=n.headers.get(Be);return r&&(t.rayId=r),t}s(ca,"trace");var la=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:ua(e),trace:ca(e,t),...r},additionalHeaders:o,statusText:ir[n.status]}),"merge"),sr=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Ve.format(e,t,r):Ve.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Pi[e],...t}}},x=class extends sr{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=la(this.getProblemFromStatus(e),t,r,o,i);return Ve.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 Q=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 W=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 Bt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=b.instance.loggingId,this.#e=e,this.#t=new W("ellie-metrics-transport",10,this.dispatchFunction,Q.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{loggingId:t,remoteLogURL:r,deploymentName:o,systemUserAgent:i}=b.instance,a=`${r}/v1/runtime/metrics`,u=e.map(l=>{let d=Object.assign({},l);return delete d.requestContentLength,delete d.responseContentLength,d.deploymentName=o,d.projectId=t,d}),c=await q.fetch(a,{method:"POST",body:JSON.stringify(u),headers:{"content-type":"application/json","zp-dn":o??"unknown","user-agent":i}});if(!c.ok){let l=await c.text();Q.getLogger(this.#e).error(`Metrics POST responded ${c.status}: ${c.statusText}`,l)}}};var oe=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=xt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},xt={name:"__system-no-version",pathPrefix:""};var me=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get(Be)??void 0,c=n.headers.get(ci)??void 0,l=e.incomingRequestProperties,d;e.route instanceof oe&&(d=e.route.systemRouteName);let p=pe.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:b.instance.instanceId,userSub:p.user?.sub,clientIp:c},f=[];return f.push(new Bt(e)),De.forEach(A=>{if(A instanceof Ze){let P=A.getTransport();f.push(P)}}),f.forEach(A=>{A.pushMetrics(g,e)}),a},"metricsProcessor");var ar=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=b.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"&&Q.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),r=new ue({processors:[me],handler:t,gateway:e}),o=new oe({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(o,r.execute)},"registerBuildRoute");var{toString:da}=Object.prototype,{propertyIsEnumerable:pa}=Object.prototype;function ur(n){return da.call(n)}s(ur,"toString");function Re(n){return typeof n=="string"}s(Re,"isString");function rt(n){return Re(n)&&n!==""}s(rt,"isNonEmptyString");function Ii(n){return ur(n)==="[object RegExp]"}s(Ii,"isRegexp");function Ei(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>pa.call(n,e))]}s(Ei,"getOwnEnumerableKeys");function Ge(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(Ge,"isObject");function cr(n){return typeof n=="number"&&!isNaN(n)}s(cr,"isNumber");function lr(n){return n===!0||n===!1}s(lr,"isBoolean");function xi(n){return typeof n>"u"}s(xi,"isUndefined");function vi(n){return xi(n)||n===null}s(vi,"isUndefinedOrNull");function vt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(vt,"isErrorLike");var Ti=new Map;function ot(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=Ti.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 Ti.set(n,r),r}s(ot,"statusCodesStringToNumberArray");function We(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 k(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(We,"getValueFromRequestUser");function Si(n,e){if(!e.startsWith("."))throw new m(`Invalid selector. must start with '.' - '${e}' does not`);let t=e.split(".").splice(1),r=n;return t.forEach(o=>{if(r===void 0)throw new k(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new k(`Error applying'${e}', reading '${o}'`)}),`${r}`}s(Si,"selectPropertyUsingJsonPath");function Ke(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(Re(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(Ke,"parseValueToStringArray");function Oi(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(!Ge(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!rt(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!cr(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&&!lr(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=dr(t,"allowedHeaders"),o=dr(t,"allowedMethods"),i=dr(t,"exposeHeaders"),a;try{a=Ke(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(Oi,"parseCorsPolicies");function dr(n,e){let t;if(n[e]!==void 0)try{t=Ke(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(dr,"parseOptionalProperty");var Vt=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"),Gt=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 pr=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 g=n.lookup(l,c);if(!g)return x.notFound(a,u);let f=g.routeConfiguration,A=ma(l,d,p,f,t);return A.isValid?new Response(void 0,{status:200,statusText:"OK",headers:A.headers}):(A.error&&u.log.warn(A.error),x.notFound(a,u))},"optionsHandler"),o=new ue({processors:[me],handler:r,gateway:e}),i=new oe({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),ma=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=Vt(a.allowedOrigins,t);return u?{isValid:!0,headers:Gt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Ai=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 ue({processors:[me],handler:t,gateway:e}),o=new oe({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 mr=new oe({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Ci=s((n,e)=>{let t=s(async(o,i)=>{let a=Pt.value?.notFoundHandler;if(a){let u=pe.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(o,i)},"notFoundHandler"),r=new ue({processors:[me],handler:t,gateway:e});n.addRoute(mr,r.execute)},"registerNotMatchedHandler");var ga=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Li=s(n=>{ga.forEach(e=>n.delete(e))},"stripCorsHeaders"),Wt=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 Li(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=fa(o,t.routeData.corsPolicies),u=ha(n,a),c=new Headers(i.headers);return Li(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"),fa=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"),ha=s((n,e)=>{let t=Vt(e.allowedOrigins,n.headers.get("origin"));return t?Gt(e,t):{}},"getCorsHeaders");var gr=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:b.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new ue({processors:[Wt],handler:t,gateway:e}),o=new oe({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(o,r.execute)},"registerPingRoute");import{SpanStatusCode as _i,trace as ki}from"@opentelemetry/api";var Ce={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 Kt=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Re(t))throw new k(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},he=class extends Kt{static{s(this,"InboundPolicy")}},qe=class extends Kt{static{s(this,"OutboundPolicy")}};var yr=class extends he{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)}},br=class extends qe{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)}},fr=new Map;function Tt(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!fr.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 he)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new yr(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}')`);fr.set(a.name,c)}),t.map(i=>{let a=fr.get(i);if(a===void 0)throw new k("Internal error. Policy not found in cache.");return a})}s(Tt,"getInboundPolicyInstances");var hr=new Map;function ya(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!hr.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 qe)u=new a(i.handler.options??{},i.name);else if(typeof a=="function")u=new br(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}'`);hr.set(i.name,u)}),t.map(o=>{let i=hr.get(o);if(i===void 0)throw new k("Internal error. Policy not found in cache.");return i})}s(ya,"getOutboundPolicyInstances");var wr=s(n=>async(e,t)=>{let r=pe.getContextExtensions(t),o=ki.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 X||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:_i.ERROR}),d.recordException(g),g}});if(l instanceof X)u=l;else if(l instanceof Request)u=new X(l);else if(l instanceof Response)return l;r.latestRequest=u}return u}finally{i.end()}})},"toStackedInboundHandler"),ba=s(n=>async(e,t,r)=>{let o=ki.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(Ce.PolicyName,c.policyName),d.setAttribute(Ce.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:_i.ERROR}),d.recordException(g),g}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),Jt=s(async(n,e,t,r)=>{let o=Tt(e.route,t.routeData.policies),i=ya(e.route,t.routeData.policies);return Di({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function Ni({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>Di({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Ni,"createInternalPolicyProcessor");async function Di({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=wr(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=ba(r),d;return b.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(Di,"executePolicyProcessor");function Mi(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||wa,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]=Ra(l,o)}i=u+1}return t}s(Mi,"parse");function wa(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(wa,"decode");function Ra(n,e){try{return e(n)}catch{return n}}s(Ra,"tryDecode");function Hi(n,e){try{let t=/v\d+(-\d+)?/g,o=Mi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s(Hi,"devPortalBaseURL");var Ui="/__zuplo/dev-portal",Pa="dev-portal-id",Ia="dev-portal-host",Ea="zp-account",xa="zp-project",va="dev-portal-build",Ta=`
25
+ import{a as Ue,d as he,e as sa,f as Mn,g as Hn,h as aa,i as ua}from"./chunk-QSL25HFO.js";import{a as tt,b as J,c as N,d as m,e as Ko,f as F,g as Jo}from"./chunk-CI735RIK.js";import{a as w}from"./chunk-HPMPWPKQ.js";import{a as s,c as et}from"./chunk-4DUPDUSC.js";Function.prototype.toString=function(){return"[native code]"};var Zt=globalThis,Yo=Zt.caches;if(Yo){let n=Yo.open;Zt.caches.open=function(e){let t=w.instance.deploymentName??w.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Zt.caches.default,Object.freeze(Zt.caches)}var Qo=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=Qo.get(e);r||(r=new Un(t),Qo.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",bt=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 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 bt(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",Be="zp-rid",qn="zp-body-removed",Ve="cf-ray",ei="x-real-ip",Fn="cf-ipcity",$n="cf-ipcontinent",jn="cf-ipcountry",zn="cf-iplongitude",Bn="cf-iplatitude",ti="cf-region",ni="cf-region-code",ri="cf-metro-code",oi="cf-postal-code",ii="cf-timezone",si="zp-ipcity",ai="zp-ipcontinent",ui="zp-ipcountry",ci="zp-iplongitude",li="zp-iplatitude",di="true-client-ip",Vn="zp-asn",Gn="zp-asorg",Wn="zp-colo",Kn="zp-postalcode",Jn="zp-metrocode",Yn="zp-region",Qn="zp-regioncode",Xn="zp-timezone",pi=[Fn,$n,jn,zn,Bn,Vn,Gn,Wn,Kn,Jn,Yn,Qn,Xn],mi=["zp-","cf-"],gi=[Be,Ve,qn];var wt="zuplo_meters_d7831150-6d8a-416d-b920-4a7bec209a49",qt="zuplo_dynamic_meters_0c8cdc26-2514-4756-8adb-474a6e103d91",Ft="system-logger";var ts=et(tt());import{trace as Va}from"@opentelemetry/api";import{SpanStatusCode as ca,trace as la}from"@opentelemetry/api";import{SpanStatusCode as rr,trace as or}from"@opentelemetry/api";var fi=s(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function hi(n){fi=n}s(hi,"setTelemetryInitFunction");var yi=s(n=>fi(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){}},$t=class extends De{static{s(this,"MeteringPlugin")}},Rt=class extends Ze{static{s(this,"TelemetryPlugin")}};var jt=new Set,bi=new Set;function h(n){bi.has(n)||(bi.add(n),jt.add(n))}s(h,"trackFeature");function wi(){let n=[...jt];return jt.clear(),n}s(wi,"getUnsentFeatures");function Ri(n){for(let e of n)jt.add(e)}s(Ri,"restoreFeatures");var Pt=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 N("Error in custom 'problemResponseFormat'",{cause:i})}})}},Ge=class{static{s(this,"ProblemResponseFormatter")}static async format(e,t,r){return await Pt.problemResponseFormat(e,t,r)}};function zt(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&zt(t)}return Object.freeze(n)}s(zt,"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 zt(this.#e)}get params(){return zt(this.#t)}user};var It={},Me=[],er=[],tr=[],nr=[];var Bt={addPlugin(n){Me.push(n)},addRequestHook(n){er.push(n)},addResponseSendingHook(n){tr.push(n)},addResponseSendingFinalHook(n){nr.push(n)}},Ii=s(async(n,e)=>{if(er.length===0)return n;let t=or.getTracer("extension");return t.startActiveSpan("hook:onRequest",async r=>{try{let o=n;for(let i of er){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:rr.ERROR}),l}});if(a instanceof ee)o=a;else return a}return o}finally{r.end()}})},"invokeOnRequestExtensions"),Ei=s(async(n,e,t)=>{if(tr.length===0)return n;let r=or.getTracer("extension");return r.startActiveSpan("hook:onResponseSending",async o=>{try{let i=n;for(let a of tr)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:rr.ERROR}),u.end(),l}});return i}finally{o.end()}})},"invokeOnResponseSendingExtensions"),xi=s(async(n,e,t)=>{if(nr.length===0)return;let r=or.getTracer("extension");return r.startActiveSpan("hook:onResponseSendingFinal",async o=>{try{for(let i of nr)await r.startActiveSpan(i.name,async a=>{try{await i(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:rr.ERROR}),a.end(),u}a.end()})}finally{o.end()}})},"invokeOnResponseSendingFinalExtensions"),Pi=!1;async function vi(n){if(!Pi){n&&(h("runtime.extensions"),await n(Bt)),It.value=Bt;for(let e of Me)if(e instanceof Rt){let{requestHandlerProxy:t}=e.instrument({accountName:w.instance.build.ACCOUNT_NAME,projectName:w.instance.build.PROJECT_NAME,buildId:w.instance.build.BUILD_ID,zuploVersion:w.instance.build.ZUPLO_VERSION,compatibilityDate:w.instance.build.COMPATIBILITY_DATE,instanceId:w.instance.instanceId,environmentType:w.instance.loggingEnvironmentType,environmentStage:w.instance.loggingEnvironmentStage,deploymentName:w.instance.deploymentName});hi(t)}for(let e of Me)e instanceof De&&await e.initialize(Bt);Pt.setProblemResponseFormat(Bt.problemResponseFormat),Pi=!0}}s(vi,"initializeRuntime");var ir={Json:"application/json",Form:"application/x-www-form-urlencoded"};function sr(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(ir.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(ir.Json)||!e?JSON.stringify(n):n}s(sr,"serialize");function rt(n){return pe.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(pe.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)=>la.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:ca.ERROR}),c}finally{a.end()}});#t=({processors:e,gateway:t,handler:r})=>async(o,i)=>{let a=[...e],u=s(async I=>{let O=a.pop();return O?O(o,i,t,u):await this.#e(async $=>{let Z=await r($,i);return da(Z)},t)(I,i)},"nextPipe"),l=await u(o),d=new URL(o.url);if(rt(d)&&w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Et(o,l);i.dispatchEvent(p);let g=me.getContextExtensions(i),f=g.latestRequest,C;try{C=await p.mutableResponse}catch(I){return i.log.error(I),t.errorHandler(o,i,I)}try{C=await g.onResponseSending(C,f,i)}catch(I){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${I.message}'`,I),t.errorHandler(o,i,I)}try{C=await Ei(C,f,i)}catch(I){return i.log.error(`Error invoking 'context.onResponseSending' hook: '${I.message}'`,I),t.errorHandler(o,i,I)}i.dispatchEvent(new xt(o,C));try{await g.onResponseSendingFinal(l,f,i)}catch(I){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${I.message}'`,I),I}try{await xi(l,f,i)}catch(I){throw i.log.error(`Error invoking 'runtime.onResponseSending' hook: '${I.message}'`,I),I}return C}};function da(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(sr(n),{headers:{"content-type":"application/json"}})}s(da,"resultToResponse");var Vt=(b=>(b[b.CONTINUE=100]="CONTINUE",b[b.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",b[b.PROCESSING=102]="PROCESSING",b[b.EARLY_HINTS=103]="EARLY_HINTS",b[b.OK=200]="OK",b[b.CREATED=201]="CREATED",b[b.ACCEPTED=202]="ACCEPTED",b[b.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",b[b.NO_CONTENT=204]="NO_CONTENT",b[b.RESET_CONTENT=205]="RESET_CONTENT",b[b.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",b[b.MULTI_STATUS=207]="MULTI_STATUS",b[b.ALREADY_REPORTED=208]="ALREADY_REPORTED",b[b.IM_USED=226]="IM_USED",b[b.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",b[b.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",b[b.FOUND=302]="FOUND",b[b.SEE_OTHER=303]="SEE_OTHER",b[b.NOT_MODIFIED=304]="NOT_MODIFIED",b[b.USE_PROXY=305]="USE_PROXY",b[b.SWITCH_PROXY=306]="SWITCH_PROXY",b[b.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",b[b.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",b[b.BAD_REQUEST=400]="BAD_REQUEST",b[b.UNAUTHORIZED=401]="UNAUTHORIZED",b[b.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",b[b.FORBIDDEN=403]="FORBIDDEN",b[b.NOT_FOUND=404]="NOT_FOUND",b[b.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",b[b.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",b[b.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",b[b.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",b[b.CONFLICT=409]="CONFLICT",b[b.GONE=410]="GONE",b[b.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",b[b.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",b[b.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",b[b.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",b[b.URI_TOO_LONG=414]="URI_TOO_LONG",b[b.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",b[b.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",b[b.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",b[b.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",b[b.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",b[b.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",b[b.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",b[b.LOCKED=423]="LOCKED",b[b.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",b[b.TOO_EARLY=425]="TOO_EARLY",b[b.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",b[b.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",b[b.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",b[b.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",b[b.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",b[b.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",b[b.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",b[b.BAD_GATEWAY=502]="BAD_GATEWAY",b[b.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",b[b.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",b[b.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",b[b.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",b[b.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",b[b.LOOP_DETECTED=508]="LOOP_DETECTED",b[b.NOT_EXTENDED=510]="NOT_EXTENDED",b[b.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",b))(Vt||{}),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 pa={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"},ar=pa;function ma(n){return`${new URL(n.url).pathname}`}s(ma,"instance");function ga(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:w.instance.build.BUILD_ID},r=n.headers.get(Ve);return r&&(t.rayId=r),t}s(ga,"trace");var fa=s((n,e,t,r,o)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:ma(e),trace:ga(e,t),...r},additionalHeaders:o,statusText:ar[n.status]}),"merge"),ur=class{static{s(this,"HttpProblemsBase")}static format=(e,t,r)=>"problem"in e?Ge.format(e,t,r):Ge.format({problem:e},t,r);static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:Ti[e],...t}}},v=class extends ur{static{s(this,"HttpProblems")}static#e(e,t,r,o,i){let a=fa(this.getProblemFromStatus(e),t,r,o,i);return Ge.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 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 J(r)}return t}static addLogger(e,t){n.#e.set(e,t)}};var K=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 Gt=class{static{s(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=w.instance.loggingId,this.#e=e,this.#t=new K("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}=w.instance,{ACCOUNT_NAME:o,PROJECT_NAME:i}=w.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=wi(),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":w.instance.deploymentName??"unknown","user-agent":w.instance.systemUserAgent}});if(!l.ok){let d=await l.text();X.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),Ri(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=vt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=o}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},vt={name:"__system-no-version",pathPrefix:""};var ge=s(async(n,e,t,r)=>{let o=new Date,i=Date.now(),a=await r(n),u=n.headers.get(Ve)??void 0,c=n.headers.get(di)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ie&&(d=e.route.systemRouteName);let p=me.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:w.instance.instanceId,userSub:p.user?.sub,clientIp:c},f=[];return f.push(new Gt(e)),Me.forEach(C=>{if(C instanceof qe){let I=C.getTransport();f.push(I)}}),f.forEach(C=>{C.pushMetrics(g,e)}),a},"metricsProcessor");var cr=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 v.notFound(i,a);let l=w.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 ce({processors:[ge],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:ha}=Object.prototype,{propertyIsEnumerable:ya}=Object.prototype;function lr(n){return ha.call(n)}s(lr,"toString");function Pe(n){return typeof n=="string"}s(Pe,"isString");function ot(n){return Pe(n)&&n!==""}s(ot,"isNonEmptyString");function Si(n){return lr(n)==="[object RegExp]"}s(Si,"isRegexp");function Oi(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>ya.call(n,e))]}s(Oi,"getOwnEnumerableKeys");function We(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}s(We,"isObject");function dr(n){return typeof n=="number"&&!isNaN(n)}s(dr,"isNumber");function pr(n){return n===!0||n===!1}s(pr,"isBoolean");function Ai(n){return typeof n>"u"}s(Ai,"isUndefined");function Ci(n){return Ai(n)||n===null}s(Ci,"isUndefinedOrNull");function Tt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}s(Tt,"isErrorLike");var Li=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=Li.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 Li.set(n,r),r}s(it,"statusCodesStringToNumberArray");function Ke(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 N(`Error applying ${t} '${e}', reading '${i}'`);o=o[i]}),`${o}`}s(Ke,"getValueFromRequestUser");function ki(n,e){if(!e.startsWith("."))throw new m(`Invalid selector. must start with '.' - '${e}' does not`);let t=e.split(".").splice(1),r=n;return t.forEach(o=>{if(r===void 0)throw new N(`Error applying'${e}', reading '${o}'`);if(r&&typeof r=="object")r=Reflect.get(r,o);else throw new N(`Error applying'${e}', reading '${o}'`)}),`${r}`}s(ki,"selectPropertyUsingJsonPath");function Je(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(Pe(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(Je,"parseValueToStringArray");function _i(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(!We(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&&!dr(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&&!pr(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=mr(t,"allowedHeaders"),o=mr(t,"allowedMethods"),i=mr(t,"exposeHeaders"),a;try{a=Je(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(_i,"parseCorsPolicies");function mr(n,e){let t;if(n[e]!==void 0)try{t=Je(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(mr,"parseOptionalProperty");var Wt=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"),Kt=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 gr=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 v.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let g=n.lookup(l,c);if(!g)return v.notFound(a,u);let f=g.routeConfiguration,C=ba(l,d,p,f,t);return C.isValid?new Response(void 0,{status:200,statusText:"OK",headers:C.headers}):(C.error&&u.log.warn(C.error),v.notFound(a,u))},"optionsHandler"),o=new ce({processors:[ge],handler:r,gateway:e}),i=new ie({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(i,o.execute)},"registerCorsRoute"),ba=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=Wt(a.allowedOrigins,t);return u?{isValid:!0,headers:Kt(a,u)}:{...i,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var Ni=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:[ge],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 fr=new ie({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Di=s((n,e)=>{let t=s(async(o,i)=>{let a=It.value?.notFoundHandler;if(a){let u=me.getContextExtensions(i);return a(o,i,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return v.notFound(o,i)},"notFoundHandler"),r=new ce({processors:[ge],handler:t,gateway:e});n.addRoute(fr,r.execute)},"registerNotMatchedHandler");var wa=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Mi=s(n=>{wa.forEach(e=>n.delete(e))},"stripCorsHeaders"),Jt=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 Mi(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 J(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof i}'`);let a=Ra(o,t.routeData.corsPolicies),u=Pa(n,a),c=new Headers(i.headers);return Mi(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"),Ra=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"),Pa=s((n,e)=>{let t=Wt(e.allowedOrigins,n.headers.get("origin"));return t?Kt(e,t):{}},"getCorsHeaders");var hr=s((n,e)=>{let t=s(async()=>new Response(JSON.stringify({buildId:w.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),r=new ce({processors:[Jt],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 Hi,trace as Ui}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 Yt=class{static{s(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Pe(t))throw new N(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ye=class extends Yt{static{s(this,"InboundPolicy")}},Fe=class extends Yt{static{s(this,"OutboundPolicy")}};var wr=class extends ye{static{s(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,r){super(t,r),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Rr=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)}},yr=new Map;function St(n,e){let t,r;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],r=n.path),t.filter(i=>!yr.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 ye)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new wr(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}')`);yr.set(a.name,c)}),t.map(i=>{let a=yr.get(i);if(a===void 0)throw new N("Internal error. Policy not found in cache.");return a})}s(St,"getInboundPolicyInstances");var br=new Map;function Ia(n,e){let t=n.policies?.outbound??[];return t.filter(o=>!br.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 Rr(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}'`);br.set(i.name,u)}),t.map(o=>{let i=br.get(o);if(i===void 0)throw new N("Internal error. Policy not found in cache.");return i})}s(Ia,"getOutboundPolicyInstances");var Pr=s(n=>async(e,t)=>{let r=me.getContextExtensions(t),o=Ui.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:Hi.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"),Ea=s(n=>async(e,t,r)=>{let o=Ui.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:Hi.ERROR}),d.recordException(g),g}}finally{d.end()}})}return u}finally{i.end()}})},"toStackedOutboundHandler"),Qt=s(async(n,e,t,r)=>{let o=St(e.route,t.routeData.policies),i=Ia(e.route,t.routeData.policies);return qi({request:n,context:e,inboundPolicies:o,outboundPolicies:i,gateway:t,next:r})},"policyProcessor");function Zi({inboundPolicies:n=[],outboundPolicies:e=[]}){return s(async(r,o,i,a)=>qi({request:r,context:o,inboundPolicies:n,outboundPolicies:e,gateway:i,next:a}),"policyProcessor")}s(Zi,"createInternalPolicyProcessor");async function qi({request:n,context:e,inboundPolicies:t,outboundPolicies:r,gateway:o,next:i}){let a=Pr(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await i(u),l=Ea(r),d;return w.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(qi,"executePolicyProcessor");function Fi(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},o=(e||{}).decode||xa,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]=va(l,o)}i=u+1}return t}s(Fi,"parse");function xa(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}s(xa,"decode");function va(n,e){try{return e(n)}catch{return n}}s(va,"tryDecode");function $i(n,e){try{let t=/v\d+(-\d+)?/g,o=Fi(e.get("Cookie")||"")["zp-dev-portal"];return o!==null&&o&&t.test(o)?`https://dev-portal-${o}.zuplo.com`:n}catch{}return n}s($i,"devPortalBaseURL");var ji="/__zuplo/dev-portal",Ta="dev-portal-id",Sa="dev-portal-host",Oa="zp-account",Aa="zp-project",Ca="dev-portal-build",La=`
26
26
  <!DOCTYPE html>
27
27
  <html lang="en">
28
28
  <head>
@@ -36,30 +36,30 @@ import{a as He,d as fe,e as ta,f as Nn,g as Dn,h as na,i as ra}from"./chunk-QSL2
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
- `,Zi=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=b.instance.deploymentName,o=b.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(b.instance.isLocalDevelopment)return new Response(Ta,{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=Hi(o,c.headers),g=new URL(`${d.pathname}${d.search}`,p),{headers:f,method:A,body:P}=c;return b.instance.build.ACCOUNT_NAME&&f.set(Ea,b.instance.build.ACCOUNT_NAME),b.instance.build.PROJECT_NAME&&f.set(xa,b.instance.build.PROJECT_NAME),f.set(Pa,r),f.set(Ia,d.host),f.set(va,b.instance.build.BUILD_ID),await q.fetch(g.toString(),{headers:f,method:A,body:P,redirect:"manual"})},"devPortalRoute"),a=new ue({processors:[me,Jt],handler:i,gateway:e}),u=new oe({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"),qi=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(Ui.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new ue({processors:[me],handler:r,gateway:e}),i=new oe({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${Ui}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var Gi=Xe(et());var Rr=0,St=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){Rr>=Number.MAX_SAFE_INTEGER&&(Rr=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:Rr++};this.#t[e](u,a)}};var ce=class extends Ue{static{s(this,"LogPlugin")}};var Yt=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 Ot=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 Sa=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),Oa=new Map(Sa);var Aa=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Pr=Symbol(".toJSON was called"),Ca=s(n=>{n[Pr]=!0;let e=n.toJSON();return delete n[Pr],e},"toJSON"),La=s(n=>Oa.get(n)??Error,"getErrorConstructor"),$i=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&&vt(n)){let l=La(n.name);t=new l}else t={};if(e.push(n),i>=o)return t;if(a&&typeof n.toJSON=="function"&&n[Pr]!==!0)return Ca(n);let c=s(l=>$i({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 Aa)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:vt(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function ye(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?$i({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}s(ye,"serializeError");var _a=/file:\/\/\/(.*?)\/dist\//g,ka="at async Event.respondWith";function Fi(n){return typeof n!="string"?n:n.split(`
40
- `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(_a,"").replaceAll(ka,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
41
- `)}s(Fi,"cleanStack");function Qt(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
+ `,zi=s((n,e)=>{let{sitePathname:t}=e.runtimeSettings.developerPortal,r=w.instance.deploymentName,o=w.instance.devPortalBaseUrl,i=s(async(c,l)=>{if(w.instance.isLocalDevelopment)return new Response(La,{headers:{"content-type":"text/html"}});if(!r)return v.internalServerError(c,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(c.url),p=$i(o,c.headers),g=new URL(`${d.pathname}${d.search}`,p),{headers:f,method:C,body:I}=c;return w.instance.build.ACCOUNT_NAME&&f.set(Oa,w.instance.build.ACCOUNT_NAME),w.instance.build.PROJECT_NAME&&f.set(Aa,w.instance.build.PROJECT_NAME),f.set(Ta,r),f.set(Sa,d.host),f.set(Ca,w.instance.build.BUILD_ID),await F.fetch(g.toString(),{headers:f,method:C,body:I,redirect:"manual"})},"devPortalRoute"),a=new ce({processors:[ge,Qt],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"),Bi=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(ji.length)}`,Response.redirect(u.toString(),302)},"devPortalRedirectRoute"),o=new ce({processors:[ge],handler:r,gateway:e}),i=new ie({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${ji}(.*)`,systemRouteName:"developer-portal-legacy"});n.addRoute(i,o.execute)},"registerDevPortalLegacyRedirectRoute");var Qi=et(tt());var Ir=0,Ot=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){Ir>=Number.MAX_SAFE_INTEGER&&(Ir=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:Ir++};this.#t[e](u,a)}};var le=class extends Ze{static{s(this,"LogPlugin")}};var Xt=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 At=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 ka=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(n=>[n.name,n]),_a=new Map(ka);var Na=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Er=Symbol(".toJSON was called"),Da=s(n=>{n[Er]=!0;let e=n.toJSON();return delete n[Er],e},"toJSON"),Ma=s(n=>_a.get(n)??Error,"getErrorConstructor"),Vi=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&&Tt(n)){let l=Ma(n.name);t=new l}else t={};if(e.push(n),i>=o)return t;if(a&&typeof n.toJSON=="function"&&n[Er]!==!0)return Da(n);let c=s(l=>Vi({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 Na)typeof n[l]<"u"&&n[l]!==null&&Object.defineProperty(t,l,{value:Tt(n[l])?c(n[l]):n[l],enumerable:r?!0:d,configurable:!0,writable:!0});return t},"destroyCircular");function be(n,e){let t=e?.maxDepth??Number.POSITIVE_INFINITY,r=e?.useToJSON??!0;return typeof n=="object"&&n!==null?Vi({from:n,seen:[],forceEnumerable:!0,maxDepth:t,depth:0,useToJSON:r,serialize:!0}):typeof n=="function"?`[Function: ${n.name??"anonymous"}]`:n}s(be,"serializeError");var Ha=/file:\/\/\/(.*?)\/dist\//g,Ua="at async Event.respondWith";function Gi(n){return typeof n!="string"?n:n.split(`
40
+ `).filter(e=>!e.trim().startsWith("at async file")).map((e,t)=>{let r=e.replaceAll(Ha,"").replaceAll(Ua,"").trim();return t===0||r.length===0?r:` ${r}`}).filter(e=>e.length>0).join(`
41
+ `)}s(Gi,"cleanStack");function en(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 A=f.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return A.length<=u.inlineCharacterLimit?A: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"||Ii(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((A,P)=>{let S=a.length-1===P?p.newline:","+p.newlineOrSpace,H=i(A,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(Ge(a)){let f=Ei(a);if(u.filter&&(f=f.filter(P=>u.filter?.(a,P))),f.length===0)return"{}";r.push(a);let A="{"+p.newline+f.map((P,S)=>{let H=f.length-1===S?p.newline:","+p.newlineOrSpace,L=typeof P=="symbol",$=!L&&/^[a-z$_][$\w]*$/i.test(P),U=L||$?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(U)+": "+F+H}).join("")+p.pad+"}";return r.pop(),g(A)}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(Qt,"stringifyObject");function $e(n){return n.map(e=>ye(e))}s($e,"makeErrorsSerializable");function it(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:Me(ye(e))}s(it,"extractBestMessage");function ji(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(vt(t))if(t.stack)e.push(t.stack);else{let r=Qt(ye(t));e.push(r)}else if(typeof t=="object"){let r=Qt(t);e.push(r)}else{let r=Ir(t);e.push(r)}}),e.join(`
46
- `)}s(ji,"messagesToMultilineText");function Me(n){return typeof n=="string"?n:JSON.stringify(n)}s(Me,"stringifyNonString");function Ir(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"?ur(n):"unknown"}s(Ir,"stringifyNonStringToText");import{importPKCS8 as Na,SignJWT as Da}from"jose";async function be(n,e,t){for(let r=0;r<=n.retries;r++){let o=q.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(be,"fetchRetry");async function Le({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new Da(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(Le,"getTokenFromGcpServiceAccount");async function zi(n,e,t){return Bi(n,{token:e,returnSecureToken:!0},t)}s(zi,"exchangeFirebaseJwtForIdToken");async function Xt(n,e,t){return Bi(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(Xt,"exchangeGgpJwtForIdToken");async function Bi(n,e,t){let r=await be(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 k({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Bi,"fetchToken");var Pe=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 Na(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 Er=class extends ce{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new At(this.options)}},Ma="https://logging.googleapis.com/v2/entries:write?alt=json",xr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},At=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=b.instance.loggingEnvironmentType,this.#i=b.instance.loggingEnvironmentStage,this.#r=b.instance.deploymentName}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Pe.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:xr[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=it(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 Pe.init(this.#e));let t=await Le({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await q.fetch(Ma,{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 W("google-log-transport",1,this.dispatchFunction)};var en="gcp";function tn(n){let e={allMessages:$e(n.messages)},t="zuplo-production",r=it(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:xr[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(tn,"gcpLogFormat");var Ct=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===en){if(e.messages.length===0)return;this.#e[e.level].apply(null,[tn(e)])}else this.#e.log(JSON.stringify(e))}};var Or=class extends ce{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new Lt(this.options)}},vr="__ddtags",Tr="__ddattr",Sr=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),Ha=s(n=>{let e=Object.keys(n),t=[];return e.forEach(r=>{let o=n[r];o==null?t.push(Sr(r)):t.push(`${Sr(r)}:${Sr(o.toString())}`)}),t.join(",")},"formatTags"),Lt=class{static{s(this,"DataDogTransport")}constructor(e){this.#e=e.apiKey,this.#t=e.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#r=b.instance.loggingEnvironmentType,this.#o=b.instance.loggingEnvironmentStage,this.#n=b.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[vr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(f=>f[vr]!==void 0);a>-1&&(Object.assign(r,i[a][vr]),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:it(d),service:e.loggingId,ddtags:Ha(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 q.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new W("data-dog-transport",10,this.dispatchFunction)};var _t=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===en){if(e.messages.length===0)return;this.#e[e.level].apply(null,[tn(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 Ua=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 q.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":b.instance.systemUserAgent,"zp-dn":b.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),nn,rn=class{static{s(this,"RemoteLogTransport")}constructor(e){nn||(nn=new W("remote-log-transport",1,Ua(e)))}log(e,t){nn.enqueue(e),t.waitUntil(nn.waitUntilFlushed())}};var Za={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Vi=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:Za[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var qa=s(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let i=Vi(t,r);try{await q.fetch(`${n}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:o.map(i)}),headers:{"content-type":"application/json",authentication:`Bearer ${e}`,"user-agent":b.instance.systemUserAgent,"zp-dn":b.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),on,sn=class{static{s(this,"UnifiedLogTransport")}constructor(e){on||(on=new W("unified-log-transport",1,qa(e)))}async log(e,t){on.enqueue(e),t.waitUntil(on.waitUntilFlushed())}};var Ar=(0,Gi.debug)("zuplo:logging"),an=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(b.instance,e),r=await n.setupUserCoreLogger(b.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Ar("Gateway.setupSystemCoreLogger");let o=[],i=t.getService(qt);return i?o.push(new _t(i.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Ct(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new sn({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 St(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Ar("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=t.getService(qt);if(a&&a.captureUserLogs===!0?r.push(new _t(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Ct(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new rn({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 At({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 Lt({apiKey:o.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:u}))}return De.forEach(u=>{u instanceof ce&&r.push(u.getTransport())}),await Promise.all(r.map(async u=>{u.init&&await u.init()})),new St(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i){Ar("Gateway.createRequestLoggers");let a=new Yt(r,o,i),u=new Ot(e,t,this.systemCoreLogger,a);return{userRequestLogger:new Ot(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var Je=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 Cr=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},kt=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},Lr=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}},Nt=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof Je||e instanceof oe))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 Cr(o,i,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new Lr(`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 kt(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 kt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var _r;function Wi(n){_r=n}s(Wi,"setGlobalZuploEventContext");function un(){if(_r===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return _r}s(un,"getGlobalZuploEventContext");function Ki({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);di.includes(o.toLowerCase())&&!pi.includes(r.toLowerCase())&&t.delete(r)}t.delete(Qo)}else li.forEach(r=>{t.delete(r)});return t}s(Ki,"normalizeIncomingRequestHeaders");var _e=(0,Ji.debug)("zuplo:runtime"),Fa=s(n=>{let e=n.findIndex(t=>t.name===xt.name);return e>-1?[...n.splice(e),xt]:[...n,xt]},"setupSystemNoVersion"),de=class n{constructor(e,t,r,o){this.routeData=e;this.runtimeSettings=t;this.schemaValidator=o;_e("Gateway.constructor"),Ce,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 an.init(r),a=e(),u={...a,corsPolicies:Oi(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=[Jt,Wt,me];#o;setupRoutes=()=>{_e("Gateway.setupRoutes");let e=this.routeData,t=Fa(e.versions),r=new Nt(t);if(e.routes.length===0)return ar(r,this),gr(r,this),pr(r,this),Ai(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(qi(r,this),Zi(r,this)),ar(r,this),gr(r,this),pr(r,this);for(let i of De)i instanceof Ne&&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 ue({processors:this.#r,handler:a,gateway:this}),c=new Je(i);r.addRoute(c,u.execute)}),Ci(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(b.instance.isWorkingCopy){if(r instanceof k&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=ye(r.cause);"stack"in i&&(i.stack=Fi(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;Wi(r);let a=Ki({headers:e.headers,removeAllVendorHeadersExceptListed:b.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(ze,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let $=new Headers(u.headers);$.set(Un,"true"),u=new Request(u,{headers:$,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 A=new cn(e.headers),P=new X(u,{params:f.params}),S=new ln({logger:l,route:f.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:A}),H=f.routeConfiguration.raw();$a.getActiveSpan()?.setAttributes({"http.route":S.route.path??S.route.pathPattern,"cloud.region":S.incomingRequestProperties.colo,[Ce.RoutePathPattern]:S.route.pathPattern,[Ce.RouteOperationId]:H.operationId,[Ce.RouteTrace]:H["x-zuplo-trace"],[Ce.RouteSystem]:nt(p)?!0:void 0});let L=pe.initialize(S,P);if(f.routeConfiguration===mr&&Pt.value?.notFoundHandler!==void 0){let $=this.#n.lookupByPathOnly(g);L.pathOnlyMatches=$.map(U=>U.routeConfiguration).filter(U=>U instanceof Je)}try{if(Q.addLogger(S,d),b.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!nt(p):!p.pathname.startsWith("/__zuplo")){let R=await yi(P,S);if(R instanceof Response)return R;{let N=pe.getContextExtensions(S);P=R,N.latestRequest=P}}nt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:f.routeConfiguration.path});let $=f.executableHandler;ja($,f,u),_e("Gateway.handleRequest - call user handler");let U=await $(P,S);if(_e("Gateway.handleRequest - user handler"),!(U instanceof Response))throw new k(`Invalid Response type from the request handler: ${typeof U}`);if(U.bodyUsed)throw new k("The response object has already been used. Return a new response instead.");let F;if(U.headers.get(ze)===null&&!U.webSocket){let R=new Headers(U.headers);R.set(ze,o),F=new Response(U.body,{status:U.status,statusText:U.statusText,headers:R,cf:U.cf})}else F=U;return F}catch($){return _e("Gateway - error executing handler",$),$ instanceof k?(l.error($),d.warn($)):d.error($),await this.#i(P,S,$)}}};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 Yi=s(async(n,e,t)=>{let r=de.instance.routeData.policies,o=Tt([n],r);if(o.length===0)throw new k(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var cn=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(zn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Bn)??void 0}get city(){return this.#e.get(Zn)??this.#e.get(oi)??void 0}get continent(){return this.#e.get(qn)??this.#e.get(ii)??void 0}get country(){return this.#e.get($n)??this.#e.get(si)??void 0}get latitude(){return this.#e.get(jn)??this.#e.get(ui)??void 0}get longitude(){return this.#e.get(Fn)??this.#e.get(ai)??void 0}get colo(){return this.#e.get(Vn)??void 0}get postalCode(){return this.#e.get(ni)??this.#e.get(Gn)??void 0}get metroCode(){return this.#e.get(ti)??this.#e.get(Wn)??void 0}get region(){return this.#e.get(Xo)??this.#e.get(Kn)??void 0}get regionCode(){return this.#e.get(ei)??this.#e.get(Jn)??void 0}get timezone(){return this.#e.get(ri)??this.#e.get(Yn)??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}}},It=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},Et=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},pe=class n{static{s(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(e,t){if(!n.#e.has(e)){let r=new n(t);return n.#e.set(e,r),r}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${e.requestId}'`)}static getContextExtensions(e){let t=n.#e.get(e);if(!t)throw new k(`Invalid state, could not get ZuploContext extensions for context with requestId '${e.requestId}'`);return t}latestRequest;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}},ln=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)=>Yi(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{pe.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{pe.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 Te=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 za}from"node:async_hooks";var Qi={request:new za};var Ba="Error initializing gateway. Check your configuration for errors or contact support.",Va="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(ze)??e.headers.get(Yo)??crypto.randomUUID(),i=e.headers.get(Be),a={requestId:o,rayId:i};return Qi.request.run(a,async()=>{b.initialize({build:this.buildEnvironment,runtime:t});try{await Ri(this.runtimeInit)}catch(c){this.handleError(c,Va,e)}return fi(s(async(c,l)=>{let d;try{d=await de.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,Ba,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:b.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var as=Xe(et());function Ga(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(Ga,"lexer");function Nr(n,e){e===void 0&&(e={});for(var t=Ga(n),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(Ka(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(R){if(c<t.length&&t[c].type===R)return t[c++].value},"tryConsume"),p=s(function(R){var N=d(R);if(N!==void 0)return N;var j=t[c],V=j.type,v=j.index;throw new TypeError("Unexpected ".concat(V," at ").concat(v,", expected ").concat(R))},"mustConsume"),g=s(function(){for(var R="",N;N=d("CHAR")||d("ESCAPED_CHAR");)R+=N;return R},"consumeText");c<t.length;){var f=d("CHAR"),A=d("NAME"),P=d("PATTERN");if(A||P){var S=f||"";o.indexOf(S)===-1&&(l+=S,S=""),l&&(a.push(l),l=""),a.push({name:A||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 L=d("OPEN");if(L){var S=g(),$=d("NAME")||"",U=d("PATTERN")||"",F=g();p("CLOSE"),a.push({name:$||(U?u++:""),pattern:$&&!U?i:U,prefix:S,suffix:F,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(Nr,"parse");function Xi(n,e){return Wa(Nr(n,e),e)}s(Xi,"compile");function Wa(n,e){e===void 0&&(e={});var t=Ja(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==="*",A=p.modifier==="*"||p.modifier==="+";if(Array.isArray(g)){if(!A)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=A?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(H))}}return l}}s(Wa,"tokensToFunction");function Ka(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(Ka,"escapeString");function Ja(n){return n&&n.sensitive?"":"i"}s(Ja,"flags");var rs=Xe(et());var Ya=(0,rs.debug)("zuplo:runtime"),Mr=new TextEncoder,es={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"},Qa=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],st=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 Hr(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){Ya("AWS fetch",e);for(let r=0;r<=this.retries;r++){let{url:o,request:i}=await this.sign(e,t),a=q.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")}},Hr=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:A,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]=Xa(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 L=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"),L.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&L.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(U=>A||!Qa.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"&&!L.has("X-Amz-Expires")&&L.set("X-Amz-Expires","86400"),L.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),L.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),L.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=ns(this.encodedPath);let $=new Set;this.encodedSearch=[...this.url.searchParams].filter(([U])=>{if(!U)return!1;if(this.service==="s3"){if($.has(U))return!1;$.add(U)}return!0}).map(U=>U.map(F=>ns(encodeURIComponent(F)))).sort(([U,F],[R,N])=>U<R?-1:U>R?1:F<N?-1:F>N?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 Dt("AWS4"+this.secretAccessKey,e),i=await Dt(o,this.region),a=await Dt(i,this.service);r=await Dt(a,"aws4_request"),this.cache.set(t,r)}return Dr(await Dt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Dr(await ts(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 g=s(f=>{if(u.inlineCharacterLimit===void 0)return f;let C=f.replace(new RegExp(p.newline,"g"),"").replace(new RegExp(p.newlineOrSpace,"g")," ").replace(new RegExp(p.pad+"|"+p.indent,"g"),"");return C.length<=u.inlineCharacterLimit?C: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"||Si(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((C,I)=>{let O=a.length-1===I?p.newline:","+p.newlineOrSpace,U=i(C,u,c+d,l+1);return u.transform&&(U=u.transform(a,I,U)),p.indent+U+O}).join("")+p.pad+"]";return r.pop(),g(f)}if(We(a)){let f=Oi(a);if(u.filter&&(f=f.filter(I=>u.filter?.(a,I))),f.length===0)return"{}";r.push(a);let C="{"+p.newline+f.map((I,O)=>{let U=f.length-1===O?p.newline:","+p.newlineOrSpace,k=typeof I=="symbol",$=!k&&/^[a-z$_][$\w]*$/i.test(I),Z=k||$?I:i(I,u,"",l+1),j=i(a[I],u,c+d,l+1);return u.transform&&(j=u.transform(a,I,j)),p.indent+String(Z)+": "+j+U}).join("")+p.pad+"}";return r.pop(),g(C)}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(en,"stringifyObject");function $e(n){return n.map(e=>be(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(be(e))}s(st,"extractBestMessage");function Wi(n){let e=[];return n.forEach(t=>{if(typeof t=="string")e.push(t);else if(Tt(t))if(t.stack)e.push(t.stack);else{let r=en(be(t));e.push(r)}else if(typeof t=="object"){let r=en(t);e.push(r)}else{let r=xr(t);e.push(r)}}),e.join(`
46
+ `)}s(Wi,"messagesToMultilineText");function He(n){return typeof n=="string"?n:JSON.stringify(n)}s(He,"stringifyNonString");function xr(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"?lr(n):"unknown"}s(xr,"stringifyNonStringToText");import{importPKCS8 as Za,SignJWT as qa}from"jose";async function we(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(we,"fetchRetry");async function ke({serviceAccount:n,audience:e,expirationTime:t="1h",payload:r={}}){let{clientEmail:o,privateKeyId:i,privateKey:a}=n;return await new qa(r).setProtectedHeader({alg:"RS256",kid:i}).setIssuer(o).setSubject(o).setAudience(e).setIssuedAt().setExpirationTime(t).sign(a)}s(ke,"getTokenFromGcpServiceAccount");async function Ki(n,e,t){return Ji(n,{token:e,returnSecureToken:!0},t)}s(Ki,"exchangeFirebaseJwtForIdToken");async function tn(n,e,t){return Ji(n,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:e},t)}s(tn,"exchangeGgpJwtForIdToken");async function Ji(n,e,t){let r=await we(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 N({message:"Could not get token from Google Identity",extensionMembers:i})}return await r.json()}s(Ji,"fetchToken");var Ie=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 Za(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 le{constructor(t){super();this.options=t}static{s(this,"GoogleCloudLoggingPlugin")}getTransport(){return new Ct(this.options)}},Fa="https://logging.googleapis.com/v2/entries:write?alt=json",Tr={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"},Ct=class{static{s(this,"GoogleLogTransport")}constructor(e){this.#n=e.logName,this.#e=e.serviceAccountJson,this.#o=w.instance.loggingEnvironmentType,this.#i=w.instance.loggingEnvironmentStage,this.#r=w.instance.deploymentName,h("logging.google-cloud")}#e;#t;#n;#r;#o;#i;async init(){this.#t=await Ie.init(this.#e)}log(e,t){if(!this.#t)throw new J("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:Tr[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 Ie.init(this.#e));let t=await ke({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),r=await F.fetch(Fa,{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 K("google-log-transport",1,this.dispatchFunction)};var nn="gcp";function rn(n){let e={allMessages:$e(n.messages)},t="zuplo-production",r=st(e.allMessages),o={logName:`projects/${t}/logs/runtime-user`,message:r,severity:Tr[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(rn,"gcpLogFormat");var Lt=class{static{s(this,"ConsoleTransport")}constructor(e,t){this.#e=e??console,this.#t=t}#e;#t;log(e){if(this.#t===nn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[rn(e)])}else this.#e.log(JSON.stringify(e))}};var Cr=class extends le{constructor(t){super();this.options=t}static{s(this,"DataDogLoggingPlugin")}getTransport(){return new kt(this.options)}},Sr="__ddtags",Or="__ddattr",Ar=s(n=>n.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),$a=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"),kt=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=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){let r={},o=t.custom[Sr];o&&typeof o=="object"&&Object.assign(r,o);let i=[...e.messages],a=e.messages.findIndex(f=>f[Sr]!==void 0);a>-1&&(Object.assign(r,i[a][Sr]),i.splice(a,1));let u={},c=t.custom[Or];c&&typeof c=="object"&&Object.assign(u,c);let l=e.messages.findIndex(f=>f[Or]!==void 0);l>-1&&(Object.assign(u,i[l][Or]),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:$a(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 F.fetch(this.#t,{method:"POST",body:JSON.stringify([...e]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new K("data-dog-transport",10,this.dispatchFunction)};var _t=class{static{s(this,"ProcessTransport")}constructor(e,t){this.#e=e,this.#t=t}#e;#t;log(e){if(this.#t===nn){if(e.messages.length===0)return;this.#e[e.level].apply(null,[rn(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 ja=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":w.instance.systemUserAgent,"zp-dn":w.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),on,sn=class{static{s(this,"RemoteLogTransport")}constructor(e){on||(on=new K("remote-log-transport",1,ja(e)))}log(e,t){on.enqueue(e),t.waitUntil(on.waitUntilFlushed())}};var za={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21},Yi=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:za[t.level],body:t.messages,attributes:r}},"unifiedFormatter");var Ba=s(({url:n,remoteLogToken:e,deploymentName:t,build:r})=>async o=>{if(o.length===0)return;let i=Yi(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":w.instance.systemUserAgent,"zp-dn":w.instance.deploymentName??"unknown"}})}catch(a){console.error(a)}},"dispatchFunction"),an,un=class{static{s(this,"UnifiedLogTransport")}constructor(e){an||(an=new K("unified-log-transport",1,Ba(e)))}async log(e,t){an.enqueue(e),t.waitUntil(an.waitUntilFlushed())}};var Lr=(0,Qi.debug)("zuplo:logging"),cn=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(w.instance,e),r=await n.setupUserCoreLogger(w.instance,e);return new n({systemCoreLogger:t,userCoreLogger:r})}static async setupSystemCoreLogger(e,t){let{build:r}=e;Lr("Gateway.setupSystemCoreLogger");let o=[],i=t.getService(Ft);return i?o.push(new _t(i.logger,e.logFormat)):e.isLocalDevelopment&&o.push(new Lt(console,e.logFormat)),e.isCloudflare&&e.deploymentName&&e.remoteLogToken&&o.push(new un({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 Ot(e.systemLogLevel,"system",e.loggingId,r.BUILD_ID,o)}static async setupUserCoreLogger(e,t){Lr("Gateway.setupUserCoreLogger");let r=[],{runtime:o,build:i}=e,a=t.getService(Ft);if(a&&a.captureUserLogs===!0?r.push(new _t(a.logger,e.logFormat)):e.isLocalDevelopment&&r.push(new Lt(console,e.logFormat)),e.remoteLogToken&&e.loggingId&&r.push(new sn({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 Ct({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 kt({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 Ot(e.userLogLevel,"user",e.loggingId,i.BUILD_ID,r)}createRequestLoggers(e,t,r,o,i){Lr("Gateway.createRequestLoggers");let a=new Xt(r,o,i),u=new At(e,t,this.systemCoreLogger,a);return{userRequestLogger:new At(e,t,this.userCoreLogger,a),systemRequestLogger:u}}};var Ye=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 kr=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},Nt=class{static{s(this,"LookupResult")}constructor(e,t,r){this.routeConfiguration=e,this.params=r??{},this.executableHandler=t}executableHandler;routeConfiguration;params},_r=class extends Error{static{s(this,"RouterError")}constructor(e,t){super(e,t)}},Dt=class{static{s(this,"Router")}constructor(e){this.routeEntries=[],this.versions=e}versions;routeEntries;addRoute(e,t){if(!(e instanceof Ye||e instanceof ie))throw new J("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 kr(o,i,e,t);Object.freeze(a.config),this.routeEntries.push(a)}catch(i){throw new _r(`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 Nt(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 Nt(o.config,o.executableHandler,a.pathname.groups);t.push(u)}}return t}};var Nr;function Xi(n){Nr=n}s(Xi,"setGlobalZuploEventContext");function ln(){if(Nr===void 0)throw new Error("global ZuploEventContext has not been defined - invalid runtime state");return Nr}s(ln,"getGlobalZuploEventContext");function es({headers:n,removeAllVendorHeadersExceptListed:e}){let t=new Headers(n);if(e){for(let[r]of n){let o=r.substring(0,3);mi.includes(o.toLowerCase())&&!gi.includes(r.toLowerCase())&&t.delete(r)}t.delete(ei)}else pi.forEach(r=>{t.delete(r)});return t}s(es,"normalizeIncomingRequestHeaders");var _e=(0,ts.debug)("zuplo:runtime"),Ga=s(n=>{let e=n.findIndex(t=>t.name===vt.name);return e>-1?[...n.splice(e),vt]:[...n,vt]},"setupSystemNoVersion"),pe=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 cn.init(r),a=e(),u={...a,corsPolicies:_i(a.corsPolicies)},c=new n(u,t,i,o);n.#e=c}if(!n.#e)throw new J("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 J("Gateway cannot be used before it is initialized");return n.#e}#t;#n;#r=[Qt,Jt,ge];#o;setupRoutes=()=>{_e("Gateway.setupRoutes");let e=this.routeData,t=Ga(e.versions),r=new Dt(t);if(e.routes.length===0)return cr(r,this),hr(r,this),gr(r,this),Ni(r,this),r;let{enabled:o}=this.runtimeSettings.developerPortal;o&&(Bi(r,this),zi(r,this)),cr(r,this),hr(r,this),gr(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 Ye(i);r.addRoute(c,u.execute)}),Di(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(w.instance.isWorkingCopy){if(r instanceof N&&r.extensionMembers)o=r.extensionMembers;else if(r.cause){let i=be(r.cause);"stack"in i&&(i.stack=Gi(i.stack)),o={cause:i}}}return v.internalServerError(e,t,{detail:r.message,...o})}async handleRequest(e,t,r){let{requestId:o,rayId:i}=t;Xi(r);let a=es({headers:e.headers,removeAllVendorHeadersExceptListed:w.instance.build.COMPATIBILITY_FLAGS.removeAllVendorHeadersExceptListed});a.set(Be,o);let u=new Request(e,{headers:a});if(["GET","HEAD"].includes(u.method)&&u.body){let $=new Headers(u.headers);$.set(qn,"true"),u=new Request(u,{headers:$,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 J(`Invalid state - no route match - should have been picked up by the not found handler, path: '${g}'`);let C=new dn(e.headers),I=new ee(u,{params:f.params}),O=new pn({logger:l,route:f.routeConfiguration,requestId:o,event:r,custom:c,incomingRequestProperties:C}),U=f.routeConfiguration.raw();Va.getActiveSpan()?.setAttributes({"http.route":O.route.path??O.route.pathPattern,"cloud.region":O.incomingRequestProperties.colo,[Le.RoutePathPattern]:O.route.pathPattern,[Le.RouteOperationId]:U.operationId,[Le.RouteTrace]:U["x-zuplo-trace"],[Le.RouteSystem]:rt(p)?!0:void 0});let k=me.initialize(O,I);if(f.routeConfiguration===fr&&It.value?.notFoundHandler!==void 0){let $=this.#n.lookupByPathOnly(g);k.pathOnlyMatches=$.map(Z=>Z.routeConfiguration).filter(Z=>Z instanceof Ye)}try{if(X.addLogger(O,d),w.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes?!rt(p):!p.pathname.startsWith("/__zuplo")){let P=await Ii(I,O);if(P instanceof Response)return P;{let D=me.getContextExtensions(O);I=P,D.latestRequest=I}}rt(p)||l.debug(`Request received '${p.pathname}'`,{method:u.method,url:p.pathname,hostname:p.hostname,route:f.routeConfiguration.path});let $=f.executableHandler;Wa($,f,u),_e("Gateway.handleRequest - call user handler");let Z=await $(I,O);if(_e("Gateway.handleRequest - user handler"),!(Z instanceof Response))throw new N(`Invalid Response type from the request handler: ${typeof Z}`);if(Z.bodyUsed)throw new N("The response object has already been used. Return a new response instead.");let j;if(Z.headers.get(Be)===null&&!Z.webSocket){let P=new Headers(Z.headers);P.set(Be,o),j=new Response(Z.body,{status:Z.status,statusText:Z.statusText,headers:P,cf:Z.cf})}else j=Z;return j}catch($){return _e("Gateway - error executing handler",$),$ instanceof N?(l.error($),d.warn($)):d.error($),await this.#i(I,O,$)}}};function Wa(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(Wa,"checkHandler");var ns=s(async(n,e,t)=>{let r=pe.instance.routeData.policies,o=St([n],r);if(o.length===0)throw new N(`Invalid 'invokeInboundPolicy call' - no policy '${n}' found.`);return o[0].handler(e,t)},"invokeInboundPolicy");var dn=class{static{s(this,"HeaderIncomingRequestProperties")}#e;constructor(e){this.#e=e}get asn(){try{let e=this.#e.get(Vn);if(typeof e=="string")return parseInt(e)}catch{}}get asOrganization(){return this.#e.get(Gn)??void 0}get city(){return this.#e.get(Fn)??this.#e.get(si)??void 0}get continent(){return this.#e.get($n)??this.#e.get(ai)??void 0}get country(){return this.#e.get(jn)??this.#e.get(ui)??void 0}get latitude(){return this.#e.get(Bn)??this.#e.get(li)??void 0}get longitude(){return this.#e.get(zn)??this.#e.get(ci)??void 0}get colo(){return this.#e.get(Wn)??void 0}get postalCode(){return this.#e.get(oi)??this.#e.get(Kn)??void 0}get metroCode(){return this.#e.get(ri)??this.#e.get(Jn)??void 0}get region(){return this.#e.get(ti)??this.#e.get(Yn)??void 0}get regionCode(){return this.#e.get(ni)??this.#e.get(Qn)??void 0}get timezone(){return this.#e.get(ii)??this.#e.get(Xn)??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}}},Et=class extends Event{static{s(this,"ResponseSendingEvent")}constructor(e,t){super("responseSending"),this.request=e,this.mutableResponse=t}request;mutableResponse},xt=class extends Event{static{s(this,"ResponseSentEvent")}constructor(e,t){super("responseSent"),this.request=e,this.response=t}request;response},me=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 N(`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}},pn=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)=>ns(u,c,this),this.waitUntil=u=>{this.#e.waitUntil(u)},this.addResponseSendingHook=u=>{me.getContextExtensions(this).addResponseSendingHook(u)},this.addResponseSendingFinalHook=u=>{me.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 Se=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 Ka}from"node:async_hooks";var rs={request:new Ka};var Ja="Error initializing gateway. Check your configuration for errors or contact support.",Ya="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.",Dr=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(Be)??e.headers.get(Xo)??crypto.randomUUID(),i=e.headers.get(Ve),a={requestId:o,rayId:i};return rs.request.run(a,async()=>{w.initialize({build:this.buildEnvironment,runtime:t});try{await vi(this.runtimeInit)}catch(c){this.handleError(c,Ya,e)}return yi(s(async(c,l)=>{let d;try{d=await pe.initialize(this.routeLoader,this.runtimeSettings,this.serviceProvider,this.schemaValidations)}catch(p){return this.handleError(p,Ja,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:w.instance.isWorkingCopy?e.message:void 0};return new Response(JSON.stringify(o,null,2),{status:500,headers:{"content-type":"application/json"}})}};var ps=et(tt());function Qa(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(Qa,"lexer");function Mr(n,e){e===void 0&&(e={});for(var t=Qa(n),r=e.prefixes,o=r===void 0?"./":r,i="[^".concat(eu(e.delimiter||"/#?"),"]+?"),a=[],u=0,c=0,l="",d=s(function(P){if(c<t.length&&t[c].type===P)return t[c++].value},"tryConsume"),p=s(function(P){var D=d(P);if(D!==void 0)return D;var z=t[c],G=z.type,T=z.index;throw new TypeError("Unexpected ".concat(G," at ").concat(T,", expected ").concat(P))},"mustConsume"),g=s(function(){for(var P="",D;D=d("CHAR")||d("ESCAPED_CHAR");)P+=D;return P},"consumeText");c<t.length;){var f=d("CHAR"),C=d("NAME"),I=d("PATTERN");if(C||I){var O=f||"";o.indexOf(O)===-1&&(l+=O,O=""),l&&(a.push(l),l=""),a.push({name:C||u++,prefix:O,suffix:"",pattern:I||i,modifier:d("MODIFIER")||""});continue}var U=f||d("ESCAPED_CHAR");if(U){l+=U;continue}l&&(a.push(l),l="");var k=d("OPEN");if(k){var O=g(),$=d("NAME")||"",Z=d("PATTERN")||"",j=g();p("CLOSE"),a.push({name:$||(Z?u++:""),pattern:$&&!Z?i:Z,prefix:O,suffix:j,modifier:d("MODIFIER")||""});continue}p("END")}return a}s(Mr,"parse");function os(n,e){return Xa(Mr(n,e),e)}s(os,"compile");function Xa(n,e){e===void 0&&(e={});var t=tu(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==="*",C=p.modifier==="*"||p.modifier==="+";if(Array.isArray(g)){if(!C)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 I=0;I<g.length;I++){var O=o(g[I],p);if(a&&!u[d].test(O))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(O,'"'));l+=p.prefix+O+p.suffix}continue}if(typeof g=="string"||typeof g=="number"){var O=o(String(g),p);if(a&&!u[d].test(O))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(O,'"'));l+=p.prefix+O+p.suffix;continue}if(!f){var U=C?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(U))}}return l}}s(Xa,"tokensToFunction");function eu(n){return n.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}s(eu,"escapeString");function tu(n){return n&&n.sensitive?"":"i"}s(tu,"flags");var us=et(tt());var nu=(0,us.debug)("zuplo:runtime"),Ur=new TextEncoder,is={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"},ru=["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){nu("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:g,appendSessionToken:f,allHeaders:C,singleEncode:I}){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 O,U;(!c||!l)&&([O,U]=ou(this.url,this.headers)),this.service=c||O||"",this.region=l||U||"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=>C||!ru.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,"/");I||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=as(this.encodedPath);let $=new Set;this.encodedSearch=[...this.url.searchParams].filter(([Z])=>{if(!Z)return!1;if(this.service==="s3"){if($.has(Z))return!1;$.add(Z)}return!0}).map(Z=>Z.map(j=>as(encodeURIComponent(j)))).sort(([Z,j],[P,D])=>Z<P?-1:Z>P?1:j<D?-1:j>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 Mt("AWS4"+this.secretAccessKey,e),i=await Mt(o,this.region),a=await Mt(i,this.service);r=await Mt(a,"aws4_request"),this.cache.set(t,r)}return Hr(await Mt(r,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,Hr(await ss(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 k("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Dr(await ts(this.body||""))}return e}};async function Dt(n,e){let t=await crypto.subtle.importKey("raw",typeof n=="string"?Mr.encode(n):n,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign"]);return crypto.subtle.sign("HMAC",t,Mr.encode(e))}s(Dt,"hmac");async function ts(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Mr.encode(n):n)}s(ts,"hash");function Dr(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Dr,"buf2hex");function ns(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(ns,"encodeRfc3986");function Xa(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 es?[es[i],a]:[i,a]}s(Xa,"guessServiceRegion");function eu(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(eu,"b64ToUint6");function os(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|=eu(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(os,"base64Decode");function dn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(dn,"uint6ToB64");function is(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(dn(o>>>18&63),dn(o>>>12&63),dn(o>>>6&63),dn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(is,"base64Encode");function at(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(at,"numberToString");function tu(n){let e=n.getTimezoneOffset(),t=Math.abs(e),r=e>0?"-":"+",o=at(Math.floor(t/60)),i=at(t%60);return`${r}${o}${i}`}s(tu,"getCLFOffset");function Ur(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=at(n.getDate()),r=e[n.getMonth()],o=n.getFullYear(),i=at(n.getHours()),a=at(n.getMinutes()),u=at(n.getSeconds()),c=tu(n);return`${t}/${r}/${o}:${i}:${a}:${u} ${c}`}s(Ur,"toCLFDate");var ss=(0,as.debug)("zuplo:runtime"),nu="X-Amzn-Trace-Id",ru="x-amzn-errortype",us=[],ou=s(async(n,e,t)=>{let r=t;for await(let o of us)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Ie=class extends k{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(nu)??void 0,this.errorType=t.get(ru)??void 0}},iu={addSendingAwsLambdaEventHook:n=>{us.push(n)}};async function su(n,e){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 st({accessKeyId:t,secretAccessKey:r}),d=`https://lambda.${o}.amazonaws.com/2015-03-31/functions/${i}/invocations`;if(ss(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,g]=await lu(n,{binaryMediaTypes:c}),{options:f}=e.route.handler,A;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?A=cu(n,e):A=await uu(n,e,{useAwsResourcePathStyle:u}),ss("Calling onSendingAwsLambdaEvent hook");let P=await ou(n,e,A);P.body=p,P.isBase64Encoded=g;let S=await l.fetch(d,{body:JSON.stringify(P)});try{return au(S)}catch(H){if(H instanceof Ie){let L=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&f.returnAmazonTraceIdHeader&&H.traceId?{AMZN_TRACE_ID_HEADER:H.traceId}:void 0;return x.internalServerError(n,e,void 0,L)}throw H}}s(su,"awsLambdaHandler");async function au(n){let e;try{e=await n.json()}catch{throw new Ie("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 Ie(e.message,n.headers):new Ie(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Ie(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 Ie(`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 Ie(`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 Ie(`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 Ie("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Ie("Response was set to base64 encoded but body was not a string",n.headers);r=os(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 Ie(`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(au,"getResponse");async function uu(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:Ur(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:pu(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(uu,"buildEventVersion1");function cu(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:Ur(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(cu,"buildEventVersion2");async function lu(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&&du(e,o)){let i=await n.arrayBuffer();t=is(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(lu,"getBodyResult");function du(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(du,"matchesContentType");function pu(n,e=!1){if(!e)return n;let t=Nr(n),r=Xi(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(pu,"getResourcePath");var mu=[502,503,504];async function ut(n,e){if(mu.includes(n.status)){let t=Q.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(ut,"logBadGatewayResponses");var Zr;function Fe(n){if(Zr===void 0){let t=b.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Zr=t}return n.log[Zr]}s(Fe,"getHandlerUserLogFunction");async function gu(n,e){let t=b.instance.build.BUILD_ID,{buildAssetsUrl:r}=b.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=fu(i);if(!a.isValid)throw new m(a.error);let u;b.instance.isLocalDevelopment?u=`${r}/${i.substring(1)}`:u=`${r}/${t}${i.substring(1)}`;let c=await q.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 ut(l,e),l}s(gu,"openApiSpecHandler");var fu=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 hu(n,e){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(hu,"redirectHandler");function yu(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(yu,"join");async function bu(n,e){let t=Fe(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=yu(u,a.pathname),l=o?`${c}${a.search}`:c.toString(),d=Date.now();t(`URL Forwarding to '${l}'`);let p=await q.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`),ut(p,e),p}s(bu,"urlForwardHandler");var wu=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 Ru(n,e){let t=Fe(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?wu(u,n.url):u,l=Date.now();t(`URL Rewriting to '${c}'`);let d=await q.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`),ut(d,e),d}s(Ru,"urlRewriteHandler");async function Pu(n,e){let t=e.route.handler.options,r=Fe(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 q.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(Pu,"webSocketHandler");var qr=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"),cs=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 ls(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 cs(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(ls,"wireUpListeners");async function Iu(n,e){let t=e.route.handler.options,r=Fe(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 q.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 A=t.policies&&t.policies.inbound?qr(t.policies.inbound,"inbound"):[],P=t.policies&&t.policies.outbound?qr(t.policies.outbound,"outbound"):[];return ls(p,f,n,e,A),ls(f,p,n,e,P),new Response(null,{status:101,webSocket:d})}s(Iu,"webSocketPipelineHandler");var $r=class extends ce{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new Fr(this.options)}},Fr=class{static{s(this,"DynaTraceTransport")}constructor(e){this.#e=e.url,this.#t=e.apiToken,this.#r=b.instance.loggingEnvironmentType,this.#o=b.instance.loggingEnvironmentStage,this.#n=b.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Me(ye(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 q.fetch(this.#e,{method:"POST",body:JSON.stringify(e),headers:{"content-type":"application/json; charset=utf-8",authorization:`Api-Token ${this.#t}`}})};batcher=new W("dyna-trace-log-transport",10,this.#i)};var jr=class extends ce{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Br(this.options)}},zr=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 Eu(n,e){return btoa(`${n}:${e}`)}s(Eu,"createBasicDigest");var Br=class{static{s(this,"LokiTransport")}constructor(e){this.#n=e.url,this.#r=Eu(e.username,e.password),this.#i=b.instance.loggingEnvironmentType,this.#s=b.instance.loggingEnvironmentStage,this.#o=b.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 zr(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:Me(ye(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 q.fetch(this.#n,{method:"POST",body:JSON.stringify(t),headers:{"content-type":"application/json",authorization:`Basic ${this.#r}`}})};batcher=new W("loki-log-transport",10,this.#u)};var Vr=class extends ce{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Gr(this.options)}},Gr=class{static{s(this,"SumoLogicTransport")}constructor(e){this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=b.instance.loggingEnvironmentType,this.#r=b.instance.loggingEnvironmentStage,this.#t=b.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:Me(ye(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 q.fetch(this.#e,{method:"POST",body:t,headers:r})};batcher=new W("sumo-logic-log-transport",10,this.#s)};var xu="d3a5b78f823648f5b1df4fe269d41172",Wr=class extends ce{constructor(t){super();this.options=t}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Kr(this.options)}},Kr=class{static{s(this,"VMWareLogInsightTransport")}constructor(e){let t;try{t=new URL(e.url),t.pathname==="/"&&(t.pathname=`/api/v1/events/ingest/${e.agentId??xu}`)}catch{throw new m(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=b.instance.loggingEnvironmentType,this.#o=b.instance.loggingEnvironmentStage,this.#n=b.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=ji(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=Ir(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 q.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 W("vmware-log-insights-log-transport",10,this.#a)};var Jr=class extends ce{constructor(t){super();this.options=t}static{s(this,"AWSLoggingPlugin")}getTransport(){return new Yr(this.options)}},Yr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new W("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}){this.awsClient=new st({accessKeyId:e,secretAccessKey:o,service:"logs",region:i}),this.logGroupName=r,this.logStreamName=t,this.region=i,this.environmentType=b.instance.loggingEnvironmentType,this.environment=b.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:Me(ye(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 Qr=new WeakMap,vu={tags:[]},Xr=class extends Ze{constructor(t){super();this.options=t}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new eo(this.options)}static setContext(t,r){let o=Qr.get(t);o||(o=vu);let i=Object.assign({...o},r);Qr.set(t,i)}},eo=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 W("data-dog-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(Qr.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 q.fetch(this.#t,{method:"POST",body:t,headers:{"content-type":"application/json","DD-API-KEY":this.#e}});if(!r.ok)throw new to(await r.text())}},to=class n extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var no=new WeakMap,Tu={dimensions:[]},ro=class extends Ze{constructor(t){super();this.options=t}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new oo(this.options)}static setContext(t,r){let o=no.get(t);o||(o=Tu);let i=Object.assign({...o},r);no.set(t,i)}},oo=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 W("dynatrace-metrics-transport",10,this.dispatchFunction,Q.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(no.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 q.fetch(this.#e,{method:"POST",body:t,headers:{"content-type":"text/plain",Authorization:`Api-Token ${this.apiToken}`}});if(!r.ok)throw new io(await r.text())}},io=class n extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var so=class{static{s(this,"AuditLogDataStaxProvider")}constructor(e){this.#e=e}#e;writeLogBatch=async e=>{await Promise.allSettled(e.map(async t=>{await q.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var ao=class extends Ne{static{s(this,"AuditLogPlugin")}constructor(e,t){super(),this.#e=e,this.#t=t}#e;#t;async initialize(e){new uo(e,this.#e,this.#t)}},ds=s(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),Su={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},uo=class{static{s(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...Su};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 W("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?ds(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?ds(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 co=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}},ke=class extends co{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var Ou="v1",Au=300;async function ps(n,e,t,r=Au,o){return await Lu(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}s(ps,"constructEventAsync");function Cu(n,e){return`${e.timestamp}.${n}`}s(Cu,"makeHMACContent");async function Lu(n,e,t,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=_u(n,e,Ou),l=/\s/.test(t),d=await Mu(Cu(a,u),t);return ku(a,i,u,d,r,c,l,o)}s(Lu,"verifyHeaderAsync");function _u(n,e,t){if(!n)throw new ke(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 ke(e,n,{message:"No stripe-signature header value was provided."});let a=e instanceof Uint8Array?o.decode(e):e,u=Nu(a,t);if(!u||u.timestamp===-1)throw new ke(a,i,{message:"Unable to extract timestamp and signatures from header"});if(!u.signatures.length)throw new ke(a,i,{message:"No signatures found with expected scheme"});return{decodedPayload:i,decodedHeader:a,details:u,suspectPayloadType:r}}s(_u,"parseEventDetails");function ku(n,e,t,r,o,i,a,u){let c=!!t.signatures.filter(g=>Du(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 N("body must be a string, ArrayBuffer or ArrayBufferView, unless you include the X-Amz-Content-Sha256 header");e=Hr(await ss(this.body||""))}return e}};async function Mt(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(Mt,"hmac");async function ss(n){return crypto.subtle.digest("SHA-256",typeof n=="string"?Ur.encode(n):n)}s(ss,"hash");function Hr(n){return Array.prototype.map.call(new Uint8Array(n),e=>("0"+e.toString(16)).slice(-2)).join("")}s(Hr,"buf2hex");function as(n){return n.replace(/[!'()*]/g,e=>"%"+e.charCodeAt(0).toString(16).toUpperCase())}s(as,"encodeRfc3986");function ou(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 is?[is[i],a]:[i,a]}s(ou,"guessServiceRegion");function iu(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(iu,"b64ToUint6");function cs(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|=iu(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(cs,"base64Decode");function mn(n){return n<26?n+65:n<52?n+71:n<62?n-4:n===62?43:n===63?47:65}s(mn,"uint6ToB64");function ls(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(mn(o>>>18&63),mn(o>>>12&63),mn(o>>>6&63),mn(o&63)),o=0);return t.substring(0,t.length-2+e)+(e===2?"":e===1?"=":"==")}s(ls,"base64Encode");function ut(n){let e=n.toString();return`${e.length===1?"0":""}${e}`}s(ut,"numberToString");function su(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(su,"getCLFOffset");function qr(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=su(n);return`${t}/${r}/${o}:${i}:${a}:${u} ${c}`}s(qr,"toCLFDate");var ds=(0,ps.debug)("zuplo:runtime"),au="X-Amzn-Trace-Id",uu="x-amzn-errortype",ms=[],cu=s(async(n,e,t)=>{let r=t;for await(let o of ms)r=await o(n,e,t);return r},"onSendingAwsLambdaEvent"),Ee=class extends N{static{s(this,"AwsLambdaError")}traceId;errorType;constructor(e,t){super(`Failed to invoke AWS Lambda function. ${e}`),this.traceId=t.get(au)??void 0,this.errorType=t.get(uu)??void 0}},lu={addSendingAwsLambdaEventHook:n=>{ms.push(n)}};async function du(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(ds(`AWS Lambda URL: ${d}`),!a)return l.fetch(d,{body:await n.arrayBuffer()});let[p,g]=await fu(n,{binaryMediaTypes:c}),{options:f}=e.route.handler,C;f&&typeof f=="object"&&"payloadFormatVersion"in f&&f.payloadFormatVersion==="2.0"?C=gu(n,e):C=await mu(n,e,{useAwsResourcePathStyle:u}),ds("Calling onSendingAwsLambdaEvent hook");let I=await cu(n,e,C);I.body=p,I.isBase64Encoded=g;let O=await l.fetch(d,{body:JSON.stringify(I)});try{return pu(O)}catch(U){if(U instanceof Ee){let k=f&&typeof f=="object"&&"returnAmazonTraceIdHeader"in f&&f.returnAmazonTraceIdHeader&&U.traceId?{AMZN_TRACE_ID_HEADER:U.traceId}:void 0;return v.internalServerError(n,e,void 0,k)}throw U}}s(du,"awsLambdaHandler");async function pu(n){let e;try{e=await n.json()}catch{throw new Ee("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 Ee(e.message,n.headers):new Ee(`Status: ${n.statusText}`,n.headers);if(e&&typeof e=="object"&&"errorMessage"in e&&typeof e.errorMessage=="string")throw new Ee(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 Ee(`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 Ee(`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 Ee(`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 Ee("Response was set to base64 encoded but no body was set",n.headers);if(typeof e.body!="string")throw new Ee("Response was set to base64 encoded but body was not a string",n.headers);r=cs(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 Ee(`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(pu,"getResponse");async function mu(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:qr(),requestTimeEpoch:new Date().valueOf(),resourceId:e.route.operationId??null,resourcePath:yu(e.route.path,t),stage:null},pathParameters:n.params,stageVariables:null}}s(mu,"buildEventVersion1");function gu(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:qr(),timeEpoch:new Date().valueOf()},pathParameters:n.params,stageVariables:null}}s(gu,"buildEventVersion2");async function fu(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&&hu(e,o)){let i=await n.arrayBuffer();t=ls(new Uint8Array(i)),r=!0}else t=await n.clone().text();return[t,r]}s(fu,"getBodyResult");function hu(n,e){let t=e.split(";")[0].trim().toLowerCase();return n.findIndex(r=>r==="*/*"?!0:r.toLowerCase()===t)>-1}s(hu,"matchesContentType");function yu(n,e=!1){if(!e)return n;let t=Mr(n),r=os(n),o={};return t.forEach(i=>{typeof i=="string"?o[i]=`{${i}}`:o[i.name]=`{${i.name}}`}),r(o)}s(yu,"getResourcePath");var bu=[502,503,504];async function ct(n,e){if(bu.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 Fr;function je(n){if(Fr===void 0){let t=w.instance.runtime.ZUPLO_HANDLER_WRITE_LOG_LEVEL;["debug","info","warn","error"].includes(t??"")||(t="debug"),Fr=t}return n.log[Fr]}s(je,"getHandlerUserLogFunction");async function wu(n,e){h("handler.open-api");let t=w.instance.build.BUILD_ID,{buildAssetsUrl:r}=w.instance,o=e.route.handler.options,{openApiFilePath:i}=o;if(!i)throw new m("Open API Spec Handler must have 'openApiFilePath' specified");let a=Ru(i);if(!a.isValid)throw new m(a.error);let u;w.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 v.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(wu,"openApiSpecHandler");var Ru=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 Pu(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(Pu,"redirectHandler");function Iu(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(Iu,"join");async function Eu(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=Iu(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}),g=Date.now()-d;return t(`URL Forward received response ${p.status} - ${p.statusText} in ${g}ms`),ct(p,e),p}s(Eu,"urlForwardHandler");var xu=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 vu(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?xu(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(vu,"urlRewriteHandler");async function Tu(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 v.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(Tu,"webSocketHandler");var $r=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"),gs=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 fs(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 gs(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(fs,"wireUpListeners");async function Su(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 v.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 O=await c.text(),U=`WebSocket connection error - ${c.status}: ${c.statusText}, content: '${O}'`;throw new Error(U)}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 C=t.policies&&t.policies.inbound?$r(t.policies.inbound,"inbound"):[],I=t.policies&&t.policies.outbound?$r(t.policies.outbound,"outbound"):[];return fs(p,f,n,e,C),fs(f,p,n,e,I),new Response(null,{status:101,webSocket:d})}s(Su,"webSocketPipelineHandler");var jr=class extends le{constructor(t){super();this.options=t}static{s(this,"DynaTraceLoggingPlugin")}getTransport(){return new zr(this.options)}},zr=class{static{s(this,"DynaTraceTransport")}constructor(e){h("logging.dynatrace"),this.#e=e.url,this.#t=e.apiToken,this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.instance.deploymentName}#e;#t;#n;#r;#o;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:He(be(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 K("dyna-trace-log-transport",10,this.#i)};var Br=class extends le{constructor(t){super();this.options=t}static{s(this,"LokiLoggingPlugin")}getTransport(){return new Gr(this.options)}},Vr=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 Ou(n,e){return btoa(`${n}:${e}`)}s(Ou,"createBasicDigest");var Gr=class{static{s(this,"LokiTransport")}constructor(e){h("logging.loki"),this.#n=e.url,this.#r=Ou(e.username,e.password),this.#i=w.instance.loggingEnvironmentType,this.#s=w.instance.loggingEnvironmentStage,this.#o=w.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 Vr(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(be(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 K("loki-log-transport",10,this.#u)};var Wr=class extends le{constructor(t){super();this.options=t}static{s(this,"SumoLogicLoggingPlugin")}getTransport(){return new Kr(this.options)}},Kr=class{static{s(this,"SumoLogicTransport")}constructor(e){h("logging.sumologic"),this.#e=e.url,this.#o=e.category,this.#i=e.name,this.#n=w.instance.loggingEnvironmentType,this.#r=w.instance.loggingEnvironmentStage,this.#t=w.instance.deploymentName}#e;#t;#n;#r;#o;#i;log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().toISOString(),message:He(be(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 K("sumo-logic-log-transport",10,this.#s)};var Au="d3a5b78f823648f5b1df4fe269d41172",Jr=class extends le{constructor(t){super();this.options=t}static{s(this,"VMWareLogInsightLoggingPlugin")}getTransport(){return new Yr(this.options)}},Yr=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??Au}`)}catch{throw new m(`Invalid option 'url' on 'VMWareLogInsightTransport' plugin. Must be a valid URL, received '${e.url}'`)}this.#e=t.toString(),this.#r=w.instance.loggingEnvironmentType,this.#o=w.instance.loggingEnvironmentStage,this.#n=w.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=Wi(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=xr(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 K("vmware-log-insights-log-transport",10,this.#a)};var Qr=class extends le{constructor(t){super();this.options=t}static{s(this,"AWSLoggingPlugin")}getTransport(){return new Xr(this.options)}},Xr=class{static{s(this,"AWSLogTransport")}awsClient;environment;environmentType;logGroupName;logStreamName;region;batcher=new K("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=w.instance.loggingEnvironmentType,this.environment=w.instance.deploymentName}log(e,t){e.messages.forEach(r=>{let o={timestamp:new Date().getTime(),message:JSON.stringify({data:He(be(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 eo=new WeakMap,Cu={tags:[]},to=class extends qe{constructor(t){super();this.options=t;h("metrics.datadog")}static{s(this,"DataDogMetricsPlugin")}getTransport(){return new no(this.options)}static setContext(t,r){let o=eo.get(t);o||(o=Cu);let i=Object.assign({...o},r);eo.set(t,i)}},no=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 K("data-dog-metrics-transport",10,this.dispatchFunction,X.getLogger(t)));let r=Math.floor(e.timestamp.getTime()/1e3),o=this.#r.concat(eo.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 ro(await r.text())}},ro=class n extends Error{static{s(this,"DataDogMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var oo=new WeakMap,Lu={dimensions:[]},io=class extends qe{constructor(t){super();this.options=t;h("metrics.dynatrace")}static{s(this,"DynatraceMetricsPlugin")}getTransport(){return new so(this.options)}static setContext(t,r){let o=oo.get(t);o||(o=Lu);let i=Object.assign({...o},r);oo.set(t,i)}},so=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 K("dynatrace-metrics-transport",10,this.dispatchFunction,X.getLogger(t)));let r=Math.floor(e.timestamp.getTime()),o=this.dimensions.concat(oo.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 ao(await r.text())}},ao=class n extends Error{static{s(this,"DynaTraceMetricsError")}constructor(e){super(e),Object.setPrototypeOf(this,n.prototype)}};var uo=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 F.fetch(this.#e.url,{method:"POST",headers:{"X-Cassandra-Token":this.#e.xCassandraToken,"content-type":"application/json"},body:JSON.stringify(t)})}))}};var co=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 lo(e,this.#e,this.#t)}},hs=s(n=>{let e={};return n.forEach((t,r)=>{e[r]=t}),e},"serializableHeaders"),ku={requestFilter:async()=>!0,include:{request:{headers:!0,body:!0},response:{headers:!0,body:!0}}},lo=class{static{s(this,"AuditPluginImpl")}constructor(e,t,r){this.#t=t;let o={...ku};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 K("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?hs(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?hs(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 po=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 po{static{s(this,"StripeSignatureVerificationError")}header;payload;constructor(e,t,r={}){super(r),this.header=e,this.payload=t}};var _u="v1",Nu=300;async function ys(n,e,t,r=Nu,o){return await Mu(n,e,t,r,o),n instanceof Uint8Array?JSON.parse(new TextDecoder("utf8").decode(n)):JSON.parse(n)}s(ys,"constructEventAsync");function Du(n,e){return`${e.timestamp}.${n}`}s(Du,"makeHMACContent");async function Mu(n,e,t,r,o){let{decodedHeader:i,decodedPayload:a,details:u,suspectPayloadType:c}=Hu(n,e,_u),l=/\s/.test(t),d=await Fu(Du(a,u),t);return Uu(a,i,u,d,r,c,l,o)}s(Mu,"verifyHeaderAsync");function Hu(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=Zu(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(Hu,"parseEventDetails");function Uu(n,e,t,r,o,i,a,u){let c=!!t.signatures.filter(g=>qu(g,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
- Note: The provided signing secret contains whitespace. This often indicates an extra newline or space is in the value`:"";if(!c)throw i?new ke(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.
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.
56
56
  Signature verification is impossible without access to the original signed material.
57
57
  `+l+`
58
- `+d}):new ke(e,n,{message:`No signatures found matching the expected signature for payload. Are you passing the raw request body you received from Stripe?
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 ke(e,n,{message:"Timestamp outside the tolerance zone"});return!0}s(ku,"validateComputedSignature");function Nu(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(Nu,"parseHeader");function Du(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(Du,"secureCompare");async function Mu(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]=lo[i[u]];return a.join("")}s(Mu,"computeHMACSignatureAsync");var lo=new Array(256);for(let n=0;n<lo.length;n++)lo[n]=n.toString(16).padStart(2,"0");function te(n,e,t="policy",r){let o=`${t} '${e}'`;if(!Ge(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 Mt=class extends he{static{s(this,"StripeWebhookVerificationInboundPolicy")}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 ps(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 ms(n){return n!==null&&typeof n=="object"&&"id"in n&&Re(n.id)&&"type"in n&&Re(n.type)}s(ms,"isStripeWebhookEvent");var Hu={getSubscription:async({subscriptionId:n,stripeSecretKey:e,logger:t})=>{let r=await q.fetch(`https://api.stripe.com/v1/subscriptions/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving subscription from Stripe API.";throw t.error(i,o),new k(i)}return o},getCustomer:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await q.fetch(`https://api.stripe.com/v1/customers/${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer from Stripe API.";throw t.error(i,o),new k(i)}return o},getUpcomingInvoice:async({customerId:n,stripeSecretKey:e,logger:t})=>{let r=await q.fetch(`https://api.stripe.com/v1/invoices/upcoming?customer=${n}`,{headers:{Authorization:`Bearer ${e}`}}),o=await r.json();if(r.status!==200){let i="Error retrieving customer upcoming invoice from Stripe API.";throw t.error(i,o),new k(i)}return o}},pn=Hu;var po="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",gs="My API Key";async function fs({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=b.instance,c=new URL(`/v1/buckets/${n}/consumers`,po);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:gs,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await be({retryDelayMs:5,retries:2,logger:Q.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 k(f)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}s(fs,"createConsumer");async function hs({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=b.instance,u=new URL(`/v1/buckets/${n}/consumers`,po);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:gs,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await be({retryDelayMs:5,retries:2,logger:Q.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 k(g)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}s(hs,"createConsumerInvite");async function ys({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=b.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,po);o.searchParams.set("with-api-key","true");let i=await be({retryDelayMs:5,retries:2,logger:Q.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 k(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(ys,"deleteConsumer");async function bs({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}=b.instance;if(!rt(p))throw new K("No Zuplo JWT token set.");let f=await be({retryDelayMs:5,retries:2,logger:Q.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 A=`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(A,P),new k(`${A} ${S}`)}n.log.info("Successfully created monetization subscription.",d)}s(bs,"createSubscription");async function ct({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=b.instance;if(!rt(o))throw new K("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:Q.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 k(`${u} ${l}`)}n.log.info(`Successfully updated monetization subscription with: '${JSON.stringify(r)}'.`)}s(ct,"updateSubscription");async function lt({context:n,stripeSubscriptionId:e,stripeCustomerId:t,meteringBucketId:r}){let{authApiJWT:o,meteringServiceUrl:i}=b.instance;if(!rt(o))throw new K("No Zuplo JWT token set.");let a=await be({retryDelayMs:5,retries:2,logger:Q.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 k(`${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 k(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 k(c)}return u.data[0]}s(lt,"getSubscription");var ne="Skipping since we're unable to process the webhook event.",je="Successfully processed the webhook event",we="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function mn(n){return n.replaceAll("_","-")}s(mn,"stripeStatusToMeteringStatus");function Ye(n){return new Date(n*1e3).toISOString()}s(Ye,"unixTimestampToISOString");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.`),x.ok(n,e,{title:ne,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:ne,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:ne,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!==b.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:ne,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.`+we});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 fs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await pn.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:ne,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await hs({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:ne,detail:p.message})}if(!c)return x.ok(n,e,{title:ne,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=mn(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:Ye(t.data.object.trial_end),trialStartDate:Ye(t.data.object.trial_start)}),await bs({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 ys({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),x.ok(n,e,{title:ne,detail:p.message})}return x.ok(n,e,{title:je})}s(mo,"onCustomerSubscriptionCreated");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 have '.data.object.id' be the subscription ID.`),x.ok(n,e,{title:ne,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:ne,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!==b.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:ne,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.`+we});try{let a=await lt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId});await ct({context:e,meteringSubscriptionId:a.id,meteringBucketId:r.meteringBucketId,requestBody:{status:"canceled",planExternalIds:a.planExternalIds}})}catch(a){return x.ok(n,e,{title:ne,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. `+we})}return x.ok(n,e,{title:je})}s(go,"onCustomerSubscriptionDeleted");async function fo(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:ne,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:ne,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!==b.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:ne,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.`+we});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 lt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=mn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=Ye(t.data.object.trial_end)),await ct({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:c,planExternalIds:u.planExternalIds,trialEndDate:l}})}catch(u){return x.ok(n,e,{title:ne,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. `+we})}return x.ok(n,e,{title:je})}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 lt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c=t.data.object.plan.product,d=(await pn.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 ct({context:e,meteringSubscriptionId:u.id,meteringBucketId:r.meteringBucketId,requestBody:{status:u.status,planExternalIds:[c],prorate:p}})}catch(u){return x.ok(n,e,{title:ne,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. `+we})}return x.ok(n,e,{title:je})}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 lt({context:e,stripeSubscriptionId:o,stripeCustomerId:i,meteringBucketId:r.meteringBucketId}),c={cancellation:{cancel_at:t.data.object.cancel_at?Ye(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?Ye(t.data.object.canceled_at):null,cancellation_details:t.data.object.cancellation_details}},l;u.metadata?l={...u.metadata,...c}:l=c,await ct({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:ne,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. `+we})}return x.ok(n,e,{title:je})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),x.ok(n,e,{title:ne,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."+we})}s(fo,"onCustomerSubscriptionUpdated");var ws=class extends $t{constructor(t){super();this.options=t}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(fe.ZUPLO_METERING_SERVICE_BUCKET_ID)d=fe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(fe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=fe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!b.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(!Uu(g))throw new m(`StripeMonetizationPlugin - The value '${g}' on the property 'primaryDataRegion' is invalid.`);let f=await c.json();if(!ms(f))return x.ok(c,l,{title:ne,detail:"The event payload received was not in the expected format. This can happen because of a misconfiguration of Stripe or your Zuplo API. "+we});switch(l.log.info(`Received Stripe webhook event of type '${f.type}' with ID '${f.id}'.`),f.type){case"customer.subscription.created":return await mo(c,l,f,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await fo(c,l,f,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await go(c,l,f,{meteringBucketId:d});default:return x.ok(c,l,{title:ne,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.`+we})}},"stripeWebhookHandler"),i=Ni({inboundPolicies:[new Mt({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 ue({processors:[me,i],handler:o,gateway:r}),u=new oe({label:"PLUGIN_STRIPE_WEBHOOK_ROUTE",methods:["POST"],path:this.options.webhooks.routePath??"/__plugins/stripe/webhooks",systemRouteName:"stripe-plugin"});t.addRoute(u,a.execute)}};function Uu(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(Uu,"isMetricsRegion");var Ps=new WeakMap,Rs={},ho=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Ps.set(e,t)}};async function Zu(n,e,t,r){if(!t.statusCodes)throw new m(`Invalid AmberfloMeterInboundPolicy '${r}': options.statusCodes must be an array of HTTP status code numbers`);let o=ot(t.statusCodes);return e.addResponseSendingFinalHook(async i=>{if(o.includes(i.status)){let a=Ps.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new k(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=We(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=Rs[t.apiKey];if(!g){let f=t.apiKey,A=n.headers.get("zm-test-id")??"";g=new W("amberflo-ingest-meter",10,async P=>{try{let S=t.url??"https://app.amberflo.io/ingest",H=await q.fetch(S,{method:"POST",body:JSON.stringify(P),headers:{"content-type":"application/json","x-api-key":f,"zm-test-id":A}});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}}),Rs[f]=g}g.enqueue(p),e.waitUntil(g.waitUntilFlushed())}}),n}s(Zu,"AmberfloMeteringInboundPolicy");async function gn(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(gn,"sha256");var Is=new Map;async function le(n,e,t){let r,o=`${n}-${e}`,i=Is.get(o);return i!==void 0?r=i:(r=`zuplo-policy-${await gn(JSON.stringify({policyName:n,options:t}))}`,Is.set(n,r)),r}s(le,"getPolicyCacheName");var Es="key-metadata-cache-type";function qu(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(qu,"getKeyValue");async function yo(n,e,t,r){if(!t.bucketName)if(fe.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=fe.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=qu(a,o);if(!u||u==="")return i("No key present");let c=await $u(u),l=await le(r,void 0,o),d=new ae(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!==Es&&Q.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let g={key:u},f=await be({retryDelayMs:5,retries:2,logger:Q.getLogger(e)},`${b.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":b.instance.deploymentName??"unknown","User-Agent":b.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 k(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${f.status}`)}let A=await f.json(),P={isValid:!0,typeId:Es,user:{sub:A.name,data:A.metadata}};return n.user=P.user,d.put(c,P,o.cacheTtlSeconds),n}s(yo,"ApiKeyInboundPolicy");async function $u(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($u,"hashValue");var Fu=yo;import{createRemoteJWKSet as zu,jwtVerify as vs}from"jose";import{createLocalJWKSet as ju}from"jose";var bo=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 wo&&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",b.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 q.fetch(e.href,{signal:i?i.signal:void 0,redirect:"manual",headers:r.headers}).catch(l=>{throw u?new Ro("JWKS fetch timed out"):l});if(a!==void 0&&clearTimeout(a),c.status!==200)throw new dt("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 dt("Failed to parse the JSON Web Key Set HTTP response as JSON")}}};function xs(n,e,t){let r=new bo(n,e,t);return async(o,i)=>r.getKey(o,i)}s(xs,"createRemoteJWKSet");var dt=class extends k{static{s(this,"JWKSError")}},wo=class extends dt{static{s(this,"JWKSNoMatchingKey")}},Ro=class extends dt{static{s(this,"JWKSTimeout")}};var fn={},Bu=s((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!fn[r.jwkUrl]){let i=!1;if("useExperimentalInMemoryCache"in r&&typeof r.useExperimentalInMemoryCache=="boolean"&&(i=r.useExperimentalInMemoryCache),i){let a=await le(n,void 0,r),u=new ae(a,e);fn[r.jwkUrl]=xs(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else fn[r.jwkUrl]=zu(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await vs(t,fn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Vu=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 vs(n,t,{issuer:e.issuer,audience:e.audience});return r},"secretVerifier"),ge=s(async(n,e,t,r)=>{let o=n.headers.get("Authorization"),i="bearer ",a=s(g=>x.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?Bu(r,e):Vu,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 A=new URL(n.url);return"code"in f&&f.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${A.pathname} `,f):e.log.warn(`Invalid token on: ${n.method} ${A.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 Gu=s(async(n,e,t,r)=>ge(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"Auth0JwtInboundPolicy");var Wu=[],Po=class n extends he{static{s(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static attributeMap;static setXacmlAttributes(e,t){n.attributeMap||(n.attributeMap=new WeakMap),n.attributeMap.set(e,{Request:t})}constructor(e,t){super(e,t),te(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Wo(e)}async handler(e,t){let r=s(a=>this.options.allowUnauthorizedRequests?e:x.forbidden(e,t,{detail:a}),"forbiddenResponse");if(e.user===void 0)return t.log.debug("No user found in request. If this is unexpected, check that you have an authentication policy before this one."),this.options.allowUnauthorizedRequests?e:x.unauthorized(e,t);let o=new URL(e.url),i=n.attributeMap?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1){let a={Attribute:[{AttributeId:"request.user.sub",Value:e.user.sub}]};i.Request.AccessSubject?i.Request.AccessSubject.push(a):i.Request.AccessSubject=[a]}if(this.options.includeDefaultActionAttributes!==!1){let a={Attribute:[{AttributeId:"request.method",Value:e.method}]};i.Request.Action?i.Request.Action.push(a):i.Request.Action=[a]}if(this.options.includeDefaultResourceAttributes!==!1){let a={Attribute:[{AttributeId:"request.scheme",Value:o.protocol},{AttributeId:"request.host",Value:o.host},{AttributeId:"request.pathname",Value:o.pathname}]};Object.entries(e.params).forEach(([u,c])=>{a.Attribute.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.Attribute.push({AttributeId:`request.query.${c}`,Value:u})}),i.Request.Action?i.Request.Action.push(a):i.Request.Action=[a]}this.populateAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:i,request:e,context:t}),this.populateAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:i,request:e,context:t}),this.populateAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:i,request:e,context:t});for(let a of Wu)i=await a(e,t,i);try{let a=await this.pdpService.makePdpRequest(i);return 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)}}populateAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,request:o,context:i}){let a=this.options[e];if(a){let u={Attribute:[]};a.forEach(c=>{let l;if("value"in c)l=c.value;else try{l=Si(o,c.valueSelector)}catch(d){throw d instanceof m?new m(`${this.policyType} '${this.policyName}' - ${d.message}`):new k(`${this.policyType} '${this.policyName}' - ${d.message}`)}l?u.Attribute.push({AttributeId:c.attributeId,Value:l}):i.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),r.Request[t]?r.Request[t].push(u):r.Request[t]=[u]}}};var Ku=s(async(n,e,t)=>{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 g=d.substring(0,p),f=d.substring(p+1),A=t.accounts.find(P=>P.username===g&&P.password===f);return A||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 hn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(hn,"extractDateElements");function Ts(n,e){return new Date(n,e+1,0).getDate()}s(Ts,"getDaysInMonth");function Io(n,e){return n<=e?e-n:6-n+e+1}s(Io,"getDaysBetweenWeekdays");var yn=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=Ts(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"?Io(d,p):Io(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=hn(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=hn(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}=hn(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 Ju={min:0,max:59},Yu={min:0,max:59},Qu={min:0,max:23},Xu={min:1,max:31},ec={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"}},tc={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},nc={"@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 Qe(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=>{Qe(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(Qe,"parseElement");function Eo(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=nc[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 yn({seconds:Qe(t,Ju),minutes:Qe(r,Yu),hours:Qe(o,Qu),days:Qe(i,Xu),months:new Set(Array.from(Qe(a,ec)).map(c=>c-1)),weekdays:new Set(Array.from(Qe(u,tc)).map(c=>c%7))})}s(Eo,"parseCronExpression");var xo=class extends he{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),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=[Eo(this.options.cronSchedule)]:this.crons=this.options.cronSchedule.map(r=>Eo(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 rc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function oc(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(oc,"digestMessage");var ic=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 oc(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 sc(n,e,t,r){let o=await le(r,t.cacheId,t),i=await caches.open(o),a=t?.cacheHttpMethods?.map(l=>l.toUpperCase())??["GET"],u=await ic(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);rc.forEach(A=>f.headers.delete(A)),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(sc,"CachingInboundPolicy");var ac=s(async(n,e,t,r)=>{if(!t.method)throw new m(`ChangeMethodInboundPolicy '${r}' options.method must be valid HttpMethod`);return new X(n,{method:t.method})},"ChangeMethodInboundPolicy");var uc=s(async(n,e,t)=>{let r=[...t.exclude??[]],o=new Headers;return r.forEach(a=>{let u=n.headers.get(a);u&&o.set(a,u)}),new X(n,{headers:o})},"ClearHeadersInboundPolicy");var cc=s(async(n,e,t,r)=>{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 lc=s(async(n,e,t,r)=>{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",ge(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var dc=s(async(n,e,t,r)=>{if(!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 ge(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 pc=s(async(n,e,t,r)=>{if(!t.policies||t.policies.length===0)throw new m(`CompositeInboundPolicy '${r}' must have valid policies defined`);let o=de.instance,i=Tt(t.policies,o?.routeData.policies);return wr(i)(n,e)},"CompositeInboundPolicy");var mc=s(async(n,e,t,r)=>{let o=n.headers.get("Authorization");if(!o)return x.unauthorized(n,e,{detail:"No authorization header"});let i=gc(o);if(!i)return x.unauthorized(n,e,{detail:"Failed to parse token from Authorization header"});let a=await le(r,void 0,t),u=new ae(a,e),c=await u.get(i);if(!c){let l=await q.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 gc(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(gc,"getToken");var fc=s(async(n,e,t,r)=>(te(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),ge(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 hc=s(async(n,e,t)=>{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 X(n,{body:JSON.stringify(u),headers:c})},"FormDataToJsonInboundPolicy");var pt="__unknown__",yc=s(async(n,e,t,r)=>{let o={allow:{countries:gt(t.allow?.countries,"allow.countries",r),regionCodes:gt(t.allow?.regionCodes,"allow.regionCode",r),asns:gt(t.allow?.asns,"allow.asOrganization",r)},block:{countries:gt(t.block?.countries,"block.countries",r),regionCodes:gt(t.block?.regionCodes,"block.regionCode",r),asns:gt(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??pt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??pt,u=e.incomingRequestProperties.asn?.toString()??pt,c=o.ignoreUnknown&&i===pt,l=o.ignoreUnknown&&a===pt,d=o.ignoreUnknown&&u===pt,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 mt(n,e,r,i,a,u);let A=o.block.countries,P=o.block.regionCodes,S=o.block.asns;return A.length>0&&A.includes(i)&&!c||P.length>0&&P.includes(a)&&!l||S.length>0&&S.includes(u)&&!d?mt(n,e,r,i,a,u):n},"GeoFilterInboundPolicy");function mt(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(mt,"blockedResponse");function gt(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(gt,"toLowerStringArray");var bc=s(async(n,e,t)=>{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 wc=s(async(n,e,t,r)=>{let o=e.route.raw().responses;if(!o)return vo(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 vo(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 Ss(a[u])}else return a.length>0?Ss(a[0]):vo(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 Ss(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(Ss,"generateResponse");var vo=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 Rc="Incoming",Pc={logRequestBody:!0,logResponseBody:!0};function Os(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(Os,"headersToObject");function As(){return new Date().toISOString()}s(As,"timestamp");var To=new WeakMap,Ic={};function Ec(n,e){let t=To.get(n);t||(t=Ic);let r=Object.assign({...t},e);To.set(n,r)}s(Ec,"setMoesifContext");async function Cs(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(Cs,"readBody");var xc={},So;function Ls(){if(!So)throw new k("Invalid State - no _lastLogger");return So}s(Ls,"getLastLogger");function vc(n){let e=xc[n];return e||(e=new W("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Ls().debug("posting",r);let o=await q.fetch("https://api.moesif.net/v1/events/batch",{method:"POST",headers:{"content-type":"application/json","X-Moesif-Application-Id":n},body:r});o.ok||Ls().error({status:o.status,body:await o.text()})})),e}s(vc,"getDispatcher");async function Tc(n,e,t,r){So=e.log;let o=As(),i=Object.assign(Pc,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Cs(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=vc(i.applicationId),d=n.headers.get("true-client-ip"),p=To.get(e)??{},g={time:o,uri:n.url,verb:n.method,body:a,ip_address:d??void 0,api_version:p.apiVersion,headers:Os(n.headers)},f=i.logResponseBody?await Cs(u,e):void 0,A={time:As(),status:u.status,headers:Os(u.headers),body:f},P={request:g,response:A,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:Rc};l.enqueue(P),e.waitUntil(l.waitUntilFlushed())}),n}s(Tc,"MoesifInboundPolicy");async function _s(n,e,t,r){let o=Q.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=b.instance,u;try{let l=await q.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(_s,"loadSubscription");async function ks(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=b.instance,u=Q.getLogger(n);try{let c=await q.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(ks,"consumeSubcriptionQuotas");var Sc=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function bn(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(bn,"validateMeters");function Ns(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=Ke(n),r=[];for(let o of t)Sc.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(Ns,"parseAllowedSubscriptionStatuses");function Ds(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(Ds,"compareMeters");var Oo=class extends he{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return Te.get(e,bt)}static setMeters(e,t){bn(t,"setMeters"),Te.set(e,Zt,t)}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=ot(this.options.meterOnStatusCodes),i=Te.get(t,Zt),a={...this.options.meters,...i};bn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Ns(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(P,S,H)=>{let L=Te.get(H,bt);if((this.options.allowRequestsWithoutSubscription??!1)&&!L){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(fe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=fe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let U=Te.get(H,Zt),F={...this.options.meters,...U};if(bn(F,this.policyName),o.includes(P.status)&&L&&F){H.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${L.id}' with meters '${JSON.stringify(F)} on response status '${P.status}'`);let{metersInSubscription:R,metersNotInSubscription:N}=Ds(L.meters,F);if(N&&Object.keys(N).length>0){let j=Object.keys(N);H.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${j}'`)}await ks(H,L.id,this.policyName,this.options.bucketId,R)}});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(fe.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=fe.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await _s(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`),Te.set(t,bt,p));let g=Te.get(t,bt);if(!g)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(g&&Object.keys(g.meters).length===0)return t.log.error(`Quota is not set up for subscription '${g.id}'`),x.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let A=Object.keys(a).filter(P=>!Object.keys(g.meters).includes(P));if(A.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${A.join(", ")}`),x.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${A.join(", ")}`,title:"Quota Exceeded"});for(let P of Object.keys(a))if(g.meters[P].available<=0&&!r)return x.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${P}'`,title:"Quota Exceeded"});return e}};var Oc=s(async(n,e,t,r)=>ge(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r),"OktaJwtInboundPolicy");import{importSPKI as Ac}from"jose";var Ao,Cc=s(async(n,e,t,r)=>{if(!Ao)try{Ao=await Ac(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return ge(n,e,{issuer:t.authUrl,secret:Ao,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var qs=Xe(et());var Hs=Xe(et());var wn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},Co=class extends wn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},Lo=class extends wn{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Lc(n,e){if(vi(n))throw new Co(e)}s(Lc,"throwIfUndefinedOrNull");function Ht(n,e){if(Lc(n,e),!Re(n))throw new Lo(e,"string")}s(Ht,"throwIfNotString");var Rn=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 Ht(e,"redisClientUrl"),Ht(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}){Ht(e,"url");let i=await q.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)}`)}},Pn=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(Ht(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 redis client only supports /rate-limit calls")}};var _c=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"),En=s(async n=>({key:`ip-${_c(n)}`}),"getIP"),xn=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),vn=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),In;function Tn(n,e){let t;if(In)return In;if(b.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),t=new Pn,In=t,t;let{authApiJWT:r,redisURL:o}=b.instance;if(!Re(o))throw new K(`RateLimitInboundPolicy '${n}' - rate limit service URL not configured`);if(!Re(r))throw new K(`RateLimitInboundPolicy '${n}' - service authentication not configured`);if(o&&(t=Rn.initialize(o,r,b.instance.deploymentName??"unknown",b.instance.systemUserAgent)),!t||!t.isEnabled())throw new K(`RateLimitInboundPolicy '${n}' - no redis ('${t}') or redis.isEnabled ('${t?.isEnabled}) is false`);return In=t,t}s(Tn,"getRedisClient");async function Sn(n,e,t,r,o){let i=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:n}),requestId:o})}s(Sn,"getCountAndUpdateExpiry");function On(n,e){let t;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(t=n.identifier.module[n.identifier.export],!t||typeof t!="function")throw new m(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await t(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new k(c)}return u},"outerFunction")}s(On,"wrapUserFunction");var An="Retry-After";var Ms=(0,Hs.debug)("zuplo:policies:RateLimitInboundPolicy"),Us=s(async(n,e,t,r)=>{let o=Q.getLogger(e),i=s((R,N)=>{let j={};return(!R||R==="retry-after")&&(j[An]=N.toString()),x.tooManyRequests(n,e,void 0,j)},"rateLimited"),u={function:On(t,r),user:xn,ip:En,all:vn}[t.rateLimitBy],c=await u(n,e,r),l=c.key,d=c.requestsAllowed??t.requestsAllowed,p=c.timeWindowMinutes??t.timeWindowMinutes,g=t.headerMode??"retry-after",f=Tn(r,o),P=`bucket/${b.instance.build.BUILD_ID}/${r}/${l}`,S=await le(r,void 0,t),H=new ae(S,e),L=Sn(P,p,f,o,e.requestId),$;s(async()=>{let R=await L;if(R.count>d){let N=Date.now()+R.ttlSeconds*1e3;H.put(P,N,R.ttlSeconds),Ms(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${P}' (async mode)`),$=i(g,R.ttlSeconds)}},"asyncCheck")();let F=await H.get(P);if(F!==void 0&&F>Date.now()){Ms(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${P}' (async mode)`);let R=Math.round((F-Date.now())/1e3);return i(g,R)}return e.addResponseSendingHook(async R=>$??R),n},"AsyncRateLimitInboundPolicy");var Zs=(0,qs.debug)("zuplo:policies:RateLimitInboundPolicy"),kc="strict",$s=s(async(n,e,t,r)=>{if((t.mode??kc)==="async")return Us(n,e,t,r);let i=Date.now(),a=Q.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[An]=d.toString()),x.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d={function:On(t,r),user:xn,ip:En,all:vn}[t.rateLimitBy],p=await d(n,e,r),g=p.key,f=p.requestsAllowed??t.requestsAllowed,A=p.timeWindowMinutes??t.timeWindowMinutes,P=t.headerMode??"retry-after",S=Tn(r,a),L=`bucket/${b.instance.build.BUILD_ID}/${r}/${g}`,$=await Sn(L,A,S,a,e.requestId);return $.count>f?(Zs(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${L}' (strict mode)`),c(P,$.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-i;Zs(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var _o;function Fs(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(Fs,"headersToNameValuePairs");function Nc(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(Nc,"queryToNameValueParis");function Dc(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(Dc,"parseIntOrUndefined");var js={};async function Mc(n,e,t,r){let o=new Date,i=Date.now();return _o||(_o={name:"zuplo",version:b.instance.build.ZUPLO_VERSION,comment:`zuplo/${b.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?We(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?We(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:b.instance.isWorkingCopy||b.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:Fs(n.headers),queryString:Nc(n.query)},response:{status:a.status,statusText:a.statusText,headers:Fs(a.headers),content:{size:Dc(n.headers.get("content-length"))}}}]}}},d=js[t.apiKey];if(!d){let p=t.apiKey;d=new W("readme-metering-inbound-policy",10,async g=>{try{let f=t.url??"https://metrics.readme.io/request",A=await q.fetch(f,{method:"POST",body:JSON.stringify(g),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});A.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${A.status}: '${await A.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(Mc,"ReadmeMetricsInboundPolicy");var Hc=s(async(n,e,t,r)=>{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 X(n,{headers:i})},"RemoveHeadersInboundPolicy");var Uc=s(async(n,e,t,r,o)=>{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 Zc=s(async(n,e,t,r)=>{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 X(i.toString(),n)},"RemoveQueryParamsInboundPolicy");var qc=s(async(n,e,t,r)=>{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 zs=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),$c=s(async(n,e,t)=>{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?zs():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?zs():n},"RequestSizeLimitInboundPolicy");var ft=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"),ht=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=Nn(t,r,o,c.name),p=de.instance.schemaValidator[d],g=p(e[c.name]),f=ko(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"),Se=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"),ko=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 Bs(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(f){let A=`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:`${A}, see errors property for more details`,errors:`${f}`});if(Oe(t.validateBody)&&Se(n,t.logLevel??"info",A,[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}`,A=x.badRequest(e,n,{detail:f});return Oe(t.validateBody)&&Se(n,t.logLevel??"info",f,[r],[f]),Ae(t.validateBody)?A:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Dn(n.route.path,e.method,o),u=de.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")}`,A=x.badRequest(e,n,{detail:f});return Oe(t.validateBody)&&Se(n,t.logLevel??"info",f,[r],[f]),Ae(t.validateBody)?A:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=ko(l),g=x.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Oe(t.validateBody)&&Se(n,t.logLevel??"info",d,[r],p),Ae(t.validateBody))return g}s(Bs,"handleBodyValidation");function Vs(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=ft(n),i=ht(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)&&Se(n,t.logLevel??"info",a,i.invalidValues,i.errors),Ae(t.validateHeaders))return u}}s(Vs,"handleHeadersValidation");function Gs(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=ft(n),o=ht(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)&&Se(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ae(t.validatePathParameters))return a}}s(Gs,"handlePathParameterValidation");function Ws(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=ft(n),o=ht(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)&&Se(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ae(t.validateQueryParameters))return a}}s(Ws,"handleQueryParameterValidation");var Ks=s(async(n,e,t)=>{let r=Ws(e,n,t);if(r!==void 0||(r=Gs(e,n,t),r!==void 0)||(r=Vs(e,n,t),r!==void 0))return r;let o=await Bs(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Fc=Ks;var jc=s(async(n,e,t,r)=>{if(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 zc=s(async(n,e,t)=>new X(n,{body:t.body}),"SetBodyInboundPolicy");var Bc=s(async(n,e,t,r)=>{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 X(n,{headers:i})},"SetHeadersInboundPolicy");var Vc=s(async(n,e,t,r,o)=>{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 Gc=s(async(n,e,t,r)=>{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 X(i.toString(),n)},"SetQueryParamsInboundPolicy");var Wc=s(async(n,e,t,r,o)=>{if(!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 Kc=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),Jc=s(async(n,e,t,r)=>{if(!t||t.sleepInMs===void 0||isNaN(t.sleepInMs))throw new m(`SleepInboundPolicy '${r} must have a valid options.sleepInMs value`);return await Kc(t.sleepInMs),n},"SleepInboundPolicy");var Yc=s(async(n,e,t,r)=>{te(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await ge(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof X))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 k(`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 Qc=s(async(n,e,t,r)=>{te(t,r).required("activeDirectoryTenantId","string").required("activeDirectoryClientId","string").required("activeDirectoryClientSecret","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number");let o=await le(r,void 0,t),i=new ae(o,e),a=await i.get(r);if(!a){let u=await Xc(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 Xc(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await be({retries:n.tokenRetries??3,retryDelayMs:10},`https://login.microsoftonline.com/${n.activeDirectoryTenantId}/oauth2/v2.0/token`,{headers:{"content-type":"application/x-www-form-urlencoded"},method:"POST",body:t});if(r.status!==200){try{let i=await r.text();e.log.error("Could not get token from Azure AD",i)}catch{}throw new k("Could not get token from Azure AD")}let o=await r.json();if(o&&typeof o=="object"&&"access_token"in o&&typeof o.access_token=="string"&&"expires_in"in o&&typeof o.expires_in=="number")return{access_token:o.access_token,expires_in:o.expires_in};throw new k("Response returned from Azure AD is not in the expected format.")}s(Xc,"getAccessToken");var Js="https://accounts.google.com/o/oauth2/token",No,el=s(async(n,e,t,r)=>{te(t,r).required("serviceAccountJson","string"),No||(No=await Pe.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 le(r,void 0,t),a=new ae(i,e),u=await a.get(r);if(!u){let c=await Le({serviceAccount:No,audience:Js,payload:o}),l=await Xt(Js,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new k("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 tl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",nl=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Do,rl=s(async(n,e,t,r)=>{if(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(nl.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Do||(Do=await Pe.init(t.serviceAccountJson));let i=t.userId;if(!i&&!t.userIdPropertyPath){if(!n.user)throw new k("Unable to set userId for upstream auth policy as request.user is 'undefined'. Do you have an authentication policy before this policy?.");i=n.user?.sub}else if(t.userIdPropertyPath){if(!n.user)throw new k(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=We(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new k(`Unable to determine user from for the policy ${r}`);let a=await le(r,void 0,t),u=new ae(a,e),c={uid:i,claims:o},l=await gn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await Le({serviceAccount:Do,audience:tl,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,f=await zi(g,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!f.idToken)throw new k("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 Mo,ol=s(async(n,e,t,r)=>{te(t,r).required("audience","string").required("serviceAccountJson","string"),Mo||(Mo=await Pe.init(t.serviceAccountJson));let o=await Le({serviceAccount:Mo,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var Ys="https://www.googleapis.com/oauth2/v4/token",Ho,il=s(async(n,e,t,r)=>{te(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Ho||(Ho=await Pe.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=Ke(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 le(r,void 0,t),a;t.useMemoryCacheOnly?a=new tt(i):a=new ae(i,e);let u=await a.get(r);if(!u){let c=await Le({serviceAccount:Ho,audience:Ys,payload:o}),l=await Xt(Ys,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new k("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new k("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 sl=s(async(n,e,t)=>{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 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 x.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var Qs=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(L,$){return $},attributeValueProcessor:function(L,$){return $},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(L,$,U){return L}},H=r(function(L){return Object.assign({},S,L)},"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",L="["+S+"]["+H+"]*",$=new RegExp("^"+L+"$"),U=r(function(R,N){let j=[],V=N.exec(R);for(;V;){let v=[];v.startIndex=N.lastIndex-V[0].length;let E=V.length;for(let M=0;M<E;M++)v.push(V[M]);j.push(v),V=N.exec(R)}return j},"getAllMatches"),F=r(function(R){let N=$.exec(R);return!(N===null||typeof N>"u")},"isName");P.isExist=function(R){return typeof R<"u"},P.isEmptyObject=function(R){return Object.keys(R).length===0},P.merge=function(R,N,j){if(N){let V=Object.keys(N),v=V.length;for(let E=0;E<v;E++)j==="strict"?R[V[E]]=[N[V[E]]]:R[V[E]]=N[V[E]]}},P.getValue=function(R){return P.isExist(R)?R:""},P.isName=F,P.getAllMatches=U,P.nameRegexp=L}}),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(L){this.tagname=L,this.child=[],this[":@"]={}}add(L,$){L==="__proto__"&&(L="#__proto__"),this.child.push({[L]:$})}addChild(L){L.tagname==="__proto__"&&(L.tagname="#__proto__"),L[":@"]&&Object.keys(L[":@"]).length>0?this.child.push({[L.tagname]:L.child,":@":L[":@"]}):this.child.push({[L.tagname]:L.child})}};S.exports=H}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(P,S){var H=a();function L(v,E){let M={};if(v[E+3]==="O"&&v[E+4]==="C"&&v[E+5]==="T"&&v[E+6]==="Y"&&v[E+7]==="P"&&v[E+8]==="E"){E=E+9;let ie=1,G=!1,J=!1,Ee="";for(;E<v.length;E++)if(v[E]==="<"&&!J){if(G&&F(v,E))E+=7,[entityName,val,E]=$(v,E+1),val.indexOf("&")===-1&&(M[V(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(G&&R(v,E))E+=8;else if(G&&N(v,E))E+=8;else if(G&&j(v,E))E+=9;else if(U)J=!0;else throw new Error("Invalid DOCTYPE");ie++,Ee=""}else if(v[E]===">"){if(J?v[E-1]==="-"&&v[E-2]==="-"&&(J=!1,ie--):ie--,ie===0)break}else v[E]==="["?G=!0:Ee+=v[E];if(ie!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:M,i:E}}s(L,"readDocType"),r(L,"readDocType");function $(v,E){let M="";for(;E<v.length&&v[E]!=="'"&&v[E]!=='"';E++)M+=v[E];if(M=M.trim(),M.indexOf(" ")!==-1)throw new Error("External entites are not supported");let ie=v[E++],G="";for(;E<v.length&&v[E]!==ie;E++)G+=v[E];return[M,G,E]}s($,"readEntityExp"),r($,"readEntityExp");function U(v,E){return v[E+1]==="!"&&v[E+2]==="-"&&v[E+3]==="-"}s(U,"isComment"),r(U,"isComment");function F(v,E){return v[E+1]==="!"&&v[E+2]==="E"&&v[E+3]==="N"&&v[E+4]==="T"&&v[E+5]==="I"&&v[E+6]==="T"&&v[E+7]==="Y"}s(F,"isEntity"),r(F,"isEntity");function R(v,E){return v[E+1]==="!"&&v[E+2]==="E"&&v[E+3]==="L"&&v[E+4]==="E"&&v[E+5]==="M"&&v[E+6]==="E"&&v[E+7]==="N"&&v[E+8]==="T"}s(R,"isElement"),r(R,"isElement");function N(v,E){return v[E+1]==="!"&&v[E+2]==="A"&&v[E+3]==="T"&&v[E+4]==="T"&&v[E+5]==="L"&&v[E+6]==="I"&&v[E+7]==="S"&&v[E+8]==="T"}s(N,"isAttlist"),r(N,"isAttlist");function j(v,E){return v[E+1]==="!"&&v[E+2]==="N"&&v[E+3]==="O"&&v[E+4]==="T"&&v[E+5]==="A"&&v[E+6]==="T"&&v[E+7]==="I"&&v[E+8]==="O"&&v[E+9]==="N"}s(j,"isNotation"),r(j,"isNotation");function V(v){if(H.isName(v))return v;throw new Error(`Invalid entity name ${v}`)}s(V,"validateEntityName"),r(V,"validateEntityName"),S.exports=L}}),l=o({"../../node_modules/strnum/strnum.js"(P,S){var H=/^[-+]?0x[a-fA-F0-9]+$/,L=/^([\-\+])?(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 $={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function U(R,N={}){if(N=Object.assign({},$,N),!R||typeof R!="string")return R;let j=R.trim();if(N.skipLike!==void 0&&N.skipLike.test(j))return R;if(N.hex&&H.test(j))return Number.parseInt(j,16);{let V=L.exec(j);if(V){let v=V[1],E=V[2],M=F(V[3]),ie=V[4]||V[6];if(!N.leadingZeros&&E.length>0&&v&&j[2]!==".")return R;if(!N.leadingZeros&&E.length>0&&!v&&j[1]!==".")return R;{let G=Number(j),J=""+G;return J.search(/[eE]/)!==-1||ie?N.eNotation?G:R:j.indexOf(".")!==-1?J==="0"&&M===""||J===M||v&&J==="-"+M?G:R:E?M===J||v+M===J?G:R:j===J||j===v+J?G:R}}else return R}}s(U,"toNumber"),r(U,"toNumber");function F(R){return R&&R.indexOf(".")!==-1&&(R=R.replace(/0+$/,""),R==="."?R="0":R[0]==="."?R="0"+R:R[R.length-1]==="."&&(R=R.substr(0,R.length-1))),R}s(F,"trimZeros"),r(F,"trimZeros"),S.exports=U}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(P,S){"use strict";var H=a(),L=u(),$=c(),U=l(),F=class{static{s(this,"OrderedObjParser")}static{r(this,"OrderedObjParser")}constructor(w){this.options=w,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,O)=>String.fromCharCode(Number.parseInt(O,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(I,O)=>String.fromCharCode(Number.parseInt(O,16))}},this.addExternalEntities=R,this.parseXml=E,this.parseTextData=N,this.resolveNameSpace=j,this.buildAttributesMap=v,this.isItStopNode=J,this.replaceEntitiesValue=ie,this.readStopNodeData=B,this.saveTextToParentTag=G,this.addChild=M}};function R(w){let I=Object.keys(w);for(let O=0;O<I.length;O++){let z=I[O];this.lastEntities[z]={regex:new RegExp("&"+z+";","g"),val:w[z]}}}s(R,"addExternalEntities"),r(R,"addExternalEntities");function N(w,I,O,z,C,_,Y){if(w!==void 0&&(this.options.trimValues&&!z&&(w=w.trim()),w.length>0)){Y||(w=this.replaceEntitiesValue(w));let Z=this.options.tagValueProcessor(I,w,O,C,_);return Z==null?w:typeof Z!=typeof w||Z!==w?Z:this.options.trimValues?se(w,this.options.parseTagValue,this.options.numberParseOptions):w.trim()===w?se(w,this.options.parseTagValue,this.options.numberParseOptions):w}}s(N,"parseTextData"),r(N,"parseTextData");function j(w){if(this.options.removeNSPrefix){let I=w.split(":"),O=w.charAt(0)==="/"?"/":"";if(I[0]==="xmlns")return"";I.length===2&&(w=O+I[1])}return w}s(j,"resolveNameSpace"),r(j,"resolveNameSpace");var V=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function v(w,I,O){if(!this.options.ignoreAttributes&&typeof w=="string"){let z=H.getAllMatches(w,V),C=z.length,_={};for(let Y=0;Y<C;Y++){let Z=this.resolveNameSpace(z[Y][1]),D=z[Y][4],re=this.options.attributeNamePrefix+Z;if(Z.length)if(this.options.transformAttributeName&&(re=this.options.transformAttributeName(re)),re==="__proto__"&&(re="#__proto__"),D!==void 0){this.options.trimValues&&(D=D.trim()),D=this.replaceEntitiesValue(D);let ee=this.options.attributeValueProcessor(Z,D,I);ee==null?_[re]=D:typeof ee!=typeof D||ee!==D?_[re]=ee:_[re]=se(D,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(_[re]=!0)}if(!Object.keys(_).length)return;if(this.options.attributesGroupName){let Y={};return Y[this.options.attributesGroupName]=_,Y}return _}}s(v,"buildAttributesMap"),r(v,"buildAttributesMap");var E=r(function(w){w=w.replace(/\r\n?/g,`
62
- `);let I=new L("!xml"),O=I,z="",C="";for(let _=0;_<w.length;_++)if(w[_]==="<")if(w[_+1]==="/"){let Z=h(w,">",_,"Closing Tag is not closed."),D=w.substring(_+2,Z).trim();if(this.options.removeNSPrefix){let ve=D.indexOf(":");ve!==-1&&(D=D.substr(ve+1))}this.options.transformTagName&&(D=this.options.transformTagName(D)),O&&(z=this.saveTextToParentTag(z,O,C));let re=C.substring(C.lastIndexOf(".")+1);if(D&&this.options.unpairedTags.indexOf(D)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${D}>`);let ee=0;re&&this.options.unpairedTags.indexOf(re)!==-1?(ee=C.lastIndexOf(".",C.lastIndexOf(".")-1),this.tagsNodeStack.pop()):ee=C.lastIndexOf("."),C=C.substring(0,ee),O=this.tagsNodeStack.pop(),z="",_=Z}else if(w[_+1]==="?"){let Z=T(w,_,!1,"?>");if(!Z)throw new Error("Pi Tag is not closed.");if(z=this.saveTextToParentTag(z,O,C),!(this.options.ignoreDeclaration&&Z.tagName==="?xml"||this.options.ignorePiTags)){let D=new L(Z.tagName);D.add(this.options.textNodeName,""),Z.tagName!==Z.tagExp&&Z.attrExpPresent&&(D[":@"]=this.buildAttributesMap(Z.tagExp,C,Z.tagName)),this.addChild(O,D,C)}_=Z.closeIndex+1}else if(w.substr(_+1,3)==="!--"){let Z=h(w,"-->",_+4,"Comment is not closed.");if(this.options.commentPropName){let D=w.substring(_+4,Z-2);z=this.saveTextToParentTag(z,O,C),O.add(this.options.commentPropName,[{[this.options.textNodeName]:D}])}_=Z}else if(w.substr(_+1,2)==="!D"){let Z=$(w,_);this.docTypeEntities=Z.entities,_=Z.i}else if(w.substr(_+1,2)==="!["){let Z=h(w,"]]>",_,"CDATA is not closed.")-2,D=w.substring(_+9,Z);z=this.saveTextToParentTag(z,O,C);let re=this.parseTextData(D,O.tagname,C,!0,!1,!0,!0);re==null&&(re=""),this.options.cdataPropName?O.add(this.options.cdataPropName,[{[this.options.textNodeName]:D}]):O.add(this.options.textNodeName,re),_=Z+2}else{let Z=T(w,_,this.options.removeNSPrefix),D=Z.tagName,re=Z.rawTagName,ee=Z.tagExp,ve=Z.attrExpPresent,Bo=Z.closeIndex;this.options.transformTagName&&(D=this.options.transformTagName(D)),O&&z&&O.tagname!=="!xml"&&(z=this.saveTextToParentTag(z,O,C,!1));let Vo=O;if(Vo&&this.options.unpairedTags.indexOf(Vo.tagname)!==-1&&(O=this.tagsNodeStack.pop(),C=C.substring(0,C.lastIndexOf("."))),D!==I.tagname&&(C+=C?"."+D:D),this.isItStopNode(this.options.stopNodes,C,D)){let xe="";if(ee.length>0&&ee.lastIndexOf("/")===ee.length-1)_=Z.closeIndex;else if(this.options.unpairedTags.indexOf(D)!==-1)_=Z.closeIndex;else{let kn=this.readStopNodeData(w,re,Bo+1);if(!kn)throw new Error(`Unexpected end of ${re}`);_=kn.i,xe=kn.tagContent}let _n=new L(D);D!==ee&&ve&&(_n[":@"]=this.buildAttributesMap(ee,C,D)),xe&&(xe=this.parseTextData(xe,D,C,!0,ve,!0,!0)),C=C.substr(0,C.lastIndexOf(".")),_n.add(this.options.textNodeName,xe),this.addChild(O,_n,C)}else{if(ee.length>0&&ee.lastIndexOf("/")===ee.length-1){D[D.length-1]==="/"?(D=D.substr(0,D.length-1),C=C.substr(0,C.length-1),ee=D):ee=ee.substr(0,ee.length-1),this.options.transformTagName&&(D=this.options.transformTagName(D));let xe=new L(D);D!==ee&&ve&&(xe[":@"]=this.buildAttributesMap(ee,C,D)),this.addChild(O,xe,C),C=C.substr(0,C.lastIndexOf("."))}else{let xe=new L(D);this.tagsNodeStack.push(O),D!==ee&&ve&&(xe[":@"]=this.buildAttributesMap(ee,C,D)),this.addChild(O,xe,C),O=xe}z="",_=Bo}}else z+=w[_];return I.child},"parseXml");function M(w,I,O){let z=this.options.updateTag(I.tagname,O,I[":@"]);z===!1||(typeof z=="string"&&(I.tagname=z),w.addChild(I))}s(M,"addChild"),r(M,"addChild");var ie=r(function(w){if(this.options.processEntities){for(let I in this.docTypeEntities){let O=this.docTypeEntities[I];w=w.replace(O.regx,O.val)}for(let I in this.lastEntities){let O=this.lastEntities[I];w=w.replace(O.regex,O.val)}if(this.options.htmlEntities)for(let I in this.htmlEntities){let O=this.htmlEntities[I];w=w.replace(O.regex,O.val)}w=w.replace(this.ampEntity.regex,this.ampEntity.val)}return w},"replaceEntitiesValue");function G(w,I,O,z){return w&&(z===void 0&&(z=Object.keys(I.child).length===0),w=this.parseTextData(w,I.tagname,O,!1,I[":@"]?Object.keys(I[":@"]).length!==0:!1,z),w!==void 0&&w!==""&&I.add(this.options.textNodeName,w),w=""),w}s(G,"saveTextToParentTag"),r(G,"saveTextToParentTag");function J(w,I,O){let z="*."+O;for(let C in w){let _=w[C];if(z===_||I===_)return!0}return!1}s(J,"isItStopNode"),r(J,"isItStopNode");function Ee(w,I,O=">"){let z,C="";for(let _=I;_<w.length;_++){let Y=w[_];if(z)Y===z&&(z="");else if(Y==='"'||Y==="'")z=Y;else if(Y===O[0])if(O[1]){if(w[_+1]===O[1])return{data:C,index:_}}else return{data:C,index:_};else Y===" "&&(Y=" ");C+=Y}}s(Ee,"tagExpWithClosingIndex"),r(Ee,"tagExpWithClosingIndex");function h(w,I,O,z){let C=w.indexOf(I,O);if(C===-1)throw new Error(z);return C+I.length-1}s(h,"findClosingIndex"),r(h,"findClosingIndex");function T(w,I,O,z=">"){let C=Ee(w,I+1,z);if(!C)return;let _=C.data,Y=C.index,Z=_.search(/\s/),D=_,re=!0;Z!==-1&&(D=_.substring(0,Z),_=_.substring(Z+1).trimStart());let ee=D;if(O){let ve=D.indexOf(":");ve!==-1&&(D=D.substr(ve+1),re=D!==C.data.substr(ve+1))}return{tagName:D,tagExp:_,closeIndex:Y,attrExpPresent:re,rawTagName:ee}}s(T,"readTagExp"),r(T,"readTagExp");function B(w,I,O){let z=O,C=1;for(;O<w.length;O++)if(w[O]==="<")if(w[O+1]==="/"){let _=h(w,">",O,`${I} is not closed`);if(w.substring(O+2,_).trim()===I&&(C--,C===0))return{tagContent:w.substring(z,O),i:_};O=_}else if(w[O+1]==="?")O=h(w,"?>",O+1,"StopNode is not closed.");else if(w.substr(O+1,3)==="!--")O=h(w,"-->",O+3,"StopNode is not closed.");else if(w.substr(O+1,2)==="![")O=h(w,"]]>",O,"StopNode is not closed.")-2;else{let _=T(w,O,">");_&&((_&&_.tagName)===I&&_.tagExp[_.tagExp.length-1]!=="/"&&C++,O=_.closeIndex)}}s(B,"readStopNodeData"),r(B,"readStopNodeData");function se(w,I,O){if(I&&typeof w=="string"){let z=w.trim();return z==="true"?!0:z==="false"?!1:U(w,O)}else return H.isExist(w)?w:""}s(se,"parseValue"),r(se,"parseValue"),S.exports=F}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(P){"use strict";function S(F,R){return H(F,R)}s(S,"prettify"),r(S,"prettify");function H(F,R,N){let j,V={};for(let v=0;v<F.length;v++){let E=F[v],M=L(E),ie="";if(N===void 0?ie=M:ie=N+"."+M,M===R.textNodeName)j===void 0?j=E[M]:j+=""+E[M];else{if(M===void 0)continue;if(E[M]){let G=H(E[M],R,ie),J=U(G,R);E[":@"]?$(G,E[":@"],ie,R):Object.keys(G).length===1&&G[R.textNodeName]!==void 0&&!R.alwaysCreateTextNode?G=G[R.textNodeName]:Object.keys(G).length===0&&(R.alwaysCreateTextNode?G[R.textNodeName]="":G=""),V[M]!==void 0&&V.hasOwnProperty(M)?(Array.isArray(V[M])||(V[M]=[V[M]]),V[M].push(G)):R.isArray(M,ie,J)?V[M]=[G]:V[M]=G}}}return typeof j=="string"?j.length>0&&(V[R.textNodeName]=j):j!==void 0&&(V[R.textNodeName]=j),V}s(H,"compress"),r(H,"compress");function L(F){let R=Object.keys(F);for(let N=0;N<R.length;N++){let j=R[N];if(j!==":@")return j}}s(L,"propName"),r(L,"propName");function $(F,R,N,j){if(R){let V=Object.keys(R),v=V.length;for(let E=0;E<v;E++){let M=V[E];j.isArray(M,N+"."+M,!0,!0)?F[M]=[R[M]]:F[M]=R[M]}}}s($,"assignAttributes"),r($,"assignAttributes");function U(F,R){let{textNodeName:N}=R,j=Object.keys(F).length;return!!(j===0||j===1&&(F[N]||typeof F[N]=="boolean"||F[N]===0))}s(U,"isLeafTag"),r(U,"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(h,T){T=Object.assign({},H,T);let B=[],se=!1,w=!1;h[0]==="\uFEFF"&&(h=h.substr(1));for(let I=0;I<h.length;I++)if(h[I]==="<"&&h[I+1]==="?"){if(I+=2,I=$(h,I),I.err)return I}else if(h[I]==="<"){let O=I;if(I++,h[I]==="!"){I=U(h,I);continue}else{let z=!1;h[I]==="/"&&(z=!0,I++);let C="";for(;I<h.length&&h[I]!==">"&&h[I]!==" "&&h[I]!==" "&&h[I]!==`
63
- `&&h[I]!=="\r";I++)C+=h[I];if(C=C.trim(),C[C.length-1]==="/"&&(C=C.substring(0,C.length-1),I--),!G(C)){let Z;return C.trim().length===0?Z="Invalid space after '<'.":Z="Tag '"+C+"' is an invalid name.",M("InvalidTag",Z,J(h,I))}let _=N(h,I);if(_===!1)return M("InvalidAttr","Attributes for '"+C+"' have open quote.",J(h,I));let Y=_.value;if(I=_.index,Y[Y.length-1]==="/"){let Z=I-Y.length;Y=Y.substring(0,Y.length-1);let D=V(Y,T);if(D===!0)se=!0;else return M(D.err.code,D.err.msg,J(h,Z+D.err.line))}else if(z)if(_.tagClosed){if(Y.trim().length>0)return M("InvalidTag","Closing tag '"+C+"' can't have attributes or invalid starting.",J(h,O));{let Z=B.pop();if(C!==Z.tagName){let D=J(h,Z.tagStartPos);return M("InvalidTag","Expected closing tag '"+Z.tagName+"' (opened in line "+D.line+", col "+D.col+") instead of closing tag '"+C+"'.",J(h,O))}B.length==0&&(w=!0)}}else return M("InvalidTag","Closing tag '"+C+"' doesn't have proper closing.",J(h,I));else{let Z=V(Y,T);if(Z!==!0)return M(Z.err.code,Z.err.msg,J(h,I-Y.length+Z.err.line));if(w===!0)return M("InvalidXml","Multiple possible root nodes found.",J(h,I));T.unpairedTags.indexOf(C)!==-1||B.push({tagName:C,tagStartPos:O}),se=!0}for(I++;I<h.length;I++)if(h[I]==="<")if(h[I+1]==="!"){I++,I=U(h,I);continue}else if(h[I+1]==="?"){if(I=$(h,++I),I.err)return I}else break;else if(h[I]==="&"){let Z=E(h,I);if(Z==-1)return M("InvalidChar","char '&' is not expected.",J(h,I));I=Z}else if(w===!0&&!L(h[I]))return M("InvalidXml","Extra text at the end",J(h,I));h[I]==="<"&&I--}}else{if(L(h[I]))continue;return M("InvalidChar","char '"+h[I]+"' is not expected.",J(h,I))}if(se){if(B.length==1)return M("InvalidTag","Unclosed tag '"+B[0].tagName+"'.",J(h,B[0].tagStartPos));if(B.length>0)return M("InvalidXml","Invalid '"+JSON.stringify(B.map(I=>I.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return M("InvalidXml","Start tag expected.",1);return!0};function L(h){return h===" "||h===" "||h===`
64
- `||h==="\r"}s(L,"isWhiteSpace"),r(L,"isWhiteSpace");function $(h,T){let B=T;for(;T<h.length;T++)if(h[T]=="?"||h[T]==" "){let se=h.substr(B,T-B);if(T>5&&se==="xml")return M("InvalidXml","XML declaration allowed only at the start of the document.",J(h,T));if(h[T]=="?"&&h[T+1]==">"){T++;break}else continue}return T}s($,"readPI"),r($,"readPI");function U(h,T){if(h.length>T+5&&h[T+1]==="-"&&h[T+2]==="-"){for(T+=3;T<h.length;T++)if(h[T]==="-"&&h[T+1]==="-"&&h[T+2]===">"){T+=2;break}}else if(h.length>T+8&&h[T+1]==="D"&&h[T+2]==="O"&&h[T+3]==="C"&&h[T+4]==="T"&&h[T+5]==="Y"&&h[T+6]==="P"&&h[T+7]==="E"){let B=1;for(T+=8;T<h.length;T++)if(h[T]==="<")B++;else if(h[T]===">"&&(B--,B===0))break}else if(h.length>T+9&&h[T+1]==="["&&h[T+2]==="C"&&h[T+3]==="D"&&h[T+4]==="A"&&h[T+5]==="T"&&h[T+6]==="A"&&h[T+7]==="["){for(T+=8;T<h.length;T++)if(h[T]==="]"&&h[T+1]==="]"&&h[T+2]===">"){T+=2;break}}return T}s(U,"readCommentAndCDATA"),r(U,"readCommentAndCDATA");var F='"',R="'";function N(h,T){let B="",se="",w=!1;for(;T<h.length;T++){if(h[T]===F||h[T]===R)se===""?se=h[T]:se!==h[T]||(se="");else if(h[T]===">"&&se===""){w=!0;break}B+=h[T]}return se!==""?!1:{value:B,index:T,tagClosed:w}}s(N,"readAttributeStr"),r(N,"readAttributeStr");var j=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function V(h,T){let B=S.getAllMatches(h,j),se={};for(let w=0;w<B.length;w++){if(B[w][1].length===0)return M("InvalidAttr","Attribute '"+B[w][2]+"' has no space in starting.",Ee(B[w]));if(B[w][3]!==void 0&&B[w][4]===void 0)return M("InvalidAttr","Attribute '"+B[w][2]+"' is without value.",Ee(B[w]));if(B[w][3]===void 0&&!T.allowBooleanAttributes)return M("InvalidAttr","boolean attribute '"+B[w][2]+"' is not allowed.",Ee(B[w]));let I=B[w][2];if(!ie(I))return M("InvalidAttr","Attribute '"+I+"' is an invalid name.",Ee(B[w]));if(!se.hasOwnProperty(I))se[I]=1;else return M("InvalidAttr","Attribute '"+I+"' is repeated.",Ee(B[w]))}return!0}s(V,"validateAttributeString"),r(V,"validateAttributeString");function v(h,T){let B=/\d/;for(h[T]==="x"&&(T++,B=/[\da-fA-F]/);T<h.length;T++){if(h[T]===";")return T;if(!h[T].match(B))break}return-1}s(v,"validateNumberAmpersand"),r(v,"validateNumberAmpersand");function E(h,T){if(T++,h[T]===";")return-1;if(h[T]==="#")return T++,v(h,T);let B=0;for(;T<h.length;T++,B++)if(!(h[T].match(/\w/)&&B<20)){if(h[T]===";")break;return-1}return T}s(E,"validateAmpersand"),r(E,"validateAmpersand");function M(h,T,B){return{err:{code:h,msg:T,line:B.line||B,col:B.col}}}s(M,"getErrorObject"),r(M,"getErrorObject");function ie(h){return S.isName(h)}s(ie,"validateAttrName"),r(ie,"validateAttrName");function G(h){return S.isName(h)}s(G,"validateTagName"),r(G,"validateTagName");function J(h,T){let B=h.substring(0,T).split(/\r?\n/);return{line:B.length,col:B[B.length-1].length+1}}s(J,"getLineNumberForPosition"),r(J,"getLineNumberForPosition");function Ee(h){return h.startIndex+h[1].length}s(Ee,"getPositionFromMatch"),r(Ee,"getPositionFromMatch")}}),f=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(P,S){var{buildOptions:H}=i(),L=d(),{prettify:$}=p(),U=g(),F=class{static{s(this,"XMLParser")}static{r(this,"XMLParser")}constructor(R){this.externalEntities={},this.options=H(R)}parse(R,N){if(typeof R!="string")if(R.toString)R=R.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(N){N===!0&&(N={});let v=U.validate(R,N);if(v!==!0)throw Error(`${v.err.msg}:${v.err.line}:${v.err.col}`)}let j=new L(this.options);j.addExternalEntities(this.externalEntities);let V=j.parseXml(R);return this.options.preserveOrder||V===void 0?V:$(V,this.options)}addEntity(R,N){if(N.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(R.indexOf("&")!==-1||R.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(N==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[R]=N}};S.exports=F}});let A=f();return new A(n)},"getXmlParser");var Uo=class extends qe{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),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?ot(e.parseOnStatusCodes):void 0,this.parser=Qs({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 k(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 Zo=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 qo=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 W(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),un().waitUntil(this.#e.waitUntilFlushed())}};var Xs=10,ea=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=ea,this.#r=Xs}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:ea,this.#r=Xs}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 al(()=>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);un().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 al(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(al,"waitUntilTrue");var Fo=["sha-1","sha-256","sha-384","sha-512"],Cn=class{static{s(this,"BaseCryptoBeta")}};var jo=class extends Cn{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(!Fo.includes(e.toLowerCase()))throw new k(`Algorithm ${e} is not supported. Try using ${Fo.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 Ln=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var zo=class extends Ln{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=b.instance.runtime.ZUPLO_KV;if(!t)throw new Go("The Key Value Store feature is not enabled for this project.");this.#e=t}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{Jr as AWSLoggingPlugin,Zu as AmberfloMeteringInboundPolicy,ho as AmberfloMeteringPolicy,Fu as ApiAuthKeyInboundPolicy,yo as ApiKeyInboundPolicy,so as AuditLogDataStaxProvider,ao as AuditLogPlugin,Gu as Auth0JwtInboundPolicy,iu as AwsLambdaHandlerExtensions,Po as AxiomaticsAuthZInboundPolicy,qo as BackgroundDispatcher,$o as BackgroundLoader,Ku as BasicAuthInboundPolicy,$s as BasicRateLimitInboundPolicy,W as BatchDispatch,xo as BrownoutInboundPolicy,sc as CachingInboundPolicy,ac as ChangeMethodInboundPolicy,uc as ClearHeadersInboundPolicy,cc as ClearHeadersOutboundPolicy,lc as ClerkJwtInboundPolicy,dc as CognitoJwtInboundPolicy,pc as CompositeInboundPolicy,m as ConfigurationError,rr as ContentTypes,Te as ContextData,jo as CryptoBeta,mc as CurityPhantomTokenInboundPolicy,Or as DataDogLoggingPlugin,Xr as DataDogMetricsPlugin,$r as DynaTraceLoggingPlugin,ro as DynatraceMetricsPlugin,fc as FirebaseJwtInboundPolicy,hc as FormDataToJsonInboundPolicy,yc as GeoFilterInboundPolicy,Er as GoogleCloudLoggingPlugin,kr as Handler,x as HttpProblems,zt as HttpStatusCode,he as InboundPolicy,bc as JWTScopeValidationInboundPolicy,zo as KeyValueStore,jr as LokiLoggingPlugin,kt as LookupResult,ae as MemoryZoneReadThroughCache,wc as MockApiInboundPolicy,Tc as MoesifInboundPolicy,Oo as MonetizationInboundPolicy,Oc as OktaJwtInboundPolicy,ge as OpenIdJwtInboundPolicy,qe as OutboundPolicy,Ve as ProblemResponseFormatter,Cc as PropelAuthJwtInboundPolicy,$s as RateLimitInboundPolicy,Mc as ReadmeMetricsInboundPolicy,Hc as RemoveHeadersInboundPolicy,Uc as RemoveHeadersOutboundPolicy,Zc as RemoveQueryParamsInboundPolicy,qc as ReplaceStringOutboundPolicy,$c as RequestSizeLimitInboundPolicy,Ks as RequestValidationInboundPolicy,jc as RequireOriginInboundPolicy,It as ResponseSendingEvent,Et as ResponseSentEvent,Nt as Router,k as RuntimeError,qt as SYSTEM_LOGGER,Fc as SchemaBasedRequestValidation,Ce as SemanticAttributes,Zo as ServiceProviderImpl,zc as SetBodyInboundPolicy,Bc as SetHeadersInboundPolicy,Vc as SetHeadersOutboundPolicy,Gc as SetQueryParamsInboundPolicy,Wc as SetStatusOutboundPolicy,Jc as SleepInboundPolicy,ws as StripeMonetizationPlugin,Mt as StripeWebhookVerificationInboundPolicy,Vr as SumoLogicLoggingPlugin,Yc as SupabaseJwtInboundPolicy,He as SystemRouteName,wt as TelemetryPlugin,Qc as UpstreamAzureAdServiceAuthInboundPolicy,el as UpstreamFirebaseAdminAuthInboundPolicy,rl as UpstreamFirebaseUserAuthInboundPolicy,ol as UpstreamGcpJwtInboundPolicy,il as UpstreamGcpServiceAuthInboundPolicy,Wr as VMWareLogInsightLoggingPlugin,sl as ValidateJsonSchemaInbound,Uo as XmlToJsonOutboundPolicy,yt as ZoneCache,X as ZuploRequest,su as awsLambdaHandler,fe as environment,Nn as getIdForParameterSchema,na as getIdForRefSchema,Dn as getIdForRequestBodySchema,ta as getRawOperationDataIdentifierName,ir as httpStatuses,gu as openApiSpecHandler,hu as redirectHandler,ra as sanitizedIdentifierName,or as serialize,Ec as setMoesifContext,bu as urlForwardHandler,Ru as urlRewriteHandler,Pu as webSocketHandler,Iu 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(Uu,"validateComputedSignature");function Zu(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(Zu,"parseHeader");function qu(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(qu,"secureCompare");async function Fu(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]=mo[i[u]];return a.join("")}s(Fu,"computeHMACSignatureAsync");var mo=new Array(256);for(let n=0;n<mo.length;n++)mo[n]=n.toString(16).padStart(2,"0");function ne(n,e,t="policy",r){let o=`${t} '${e}'`;if(!We(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(ne,"optionValidator");var Ht=class extends ye{static{s(this,"StripeWebhookVerificationInboundPolicy")}constructor(e,t){super(e,t),h("policy.inbound.stripe-webhook-verification")}async handler(e,t){ne(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 ys(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),v.badRequest(e,t,{title:"Webhook Error",detail:i})}return e}};function bs(n){return n!==null&&typeof n=="object"&&"id"in n&&Pe(n.id)&&"type"in n&&Pe(n.type)}s(bs,"isStripeWebhookEvent");var $u={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 N(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 N(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 N(i)}return o}},gn=$u;var go="https://api-key-management-service-eq7z4lly2a-ue.a.run.app",ws="My API Key";async function Rs({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,managerSub:i,context:a}){let{authApiJWT:u}=w.instance,c=new URL(`/v1/buckets/${n}/consumers`,go);c.searchParams.set("with-api-key","true");let l=crypto.randomUUID(),d={name:l,description:ws,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[{sub:i,email:o}]},p=await we({retryDelayMs:5,retries:2,logger:X.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 N(f)}return a.log.info("Successfully created API Key Consumer",{consumerId:l,stripeSubscriptionId:e,stripeProductId:t}),l}s(Rs,"createConsumer");async function Ps({apiKeyBucketName:n,stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r,managerEmail:o,context:i}){let{authApiJWT:a}=w.instance,u=new URL(`/v1/buckets/${n}/consumers`,go);u.searchParams.set("with-api-key","true");let c=crypto.randomUUID(),l={name:c,description:ws,tags:{subscriptionExternalId:e,planExternalIds:[t]},metadata:{stripeSubscriptionId:e,stripeProductId:t,stripeCustomerId:r},managers:[o]},d=await we({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 g="Error creating API Key Consumer";throw i.log.error(g,p),new N(g)}return i.log.info("Successfully created API Key Consumer with Manager Invite",{consumerId:c,stripeSubscriptionId:e,stripeProductId:t}),c}s(Ps,"createConsumerInvite");async function Is({apiKeyBucketName:n,consumerId:e,context:t}){let{authApiJWT:r}=w.instance,o=new URL(`/v1/buckets/${n}/consumers/${e}`,go);o.searchParams.set("with-api-key","true");let i=await we({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 N(u)}return t.log.info(`Successfully invalidated API Key Consumer '${e}`),e}s(Is,"deleteConsumer");async function Es({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}=w.instance;if(!ot(p))throw new J("No Zuplo JWT token set.");let f=await we({retryDelayMs:5,retries:2,logger:X.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 C=`Unable to create a monetization subscription for Stripe subscription '${e}'.`,I,O="";try{I=await f.json(),O=I.detail??I.title}catch{I={type:"https://zup.fail/http-status/500",title:"Internal Server Error",status:f.status,detail:f.statusText}}throw n.log.error(C,I),new N(`${C} ${O}`)}n.log.info("Successfully created monetization subscription.",d)}s(Es,"createSubscription");async function lt({context:n,meteringSubscriptionId:e,meteringBucketId:t,requestBody:r}){let{authApiJWT:o,meteringServiceUrl:i}=w.instance;if(!ot(o))throw new J("No Zuplo JWT token set.");let a=await we({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 N(`${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}=w.instance;if(!ot(o))throw new J("No Zuplo JWT token set.");let a=await we({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 N(`${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 N(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 N(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",Re="See https://zuplo.com/docs/articles/monetization-troubleshooting for more details.";function fn(n){return n.replaceAll("_","-")}s(fn,"stripeStatusToMeteringStatus");function Qe(n){return new Date(n*1e3).toISOString()}s(Qe,"unixTimestampToISOString");async function fo(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.`),v.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.`),v.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}'`),v.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!==w.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}'.`),v.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.`+Re});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 Rs({apiKeyBucketName:r.apiKeyBucketName,stripeProductId:u,stripeSubscriptionId:o,stripeCustomerId:a,managerEmail:l,managerSub:d,context:e});else{let p=await gn.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.`),v.ok(n,e,{title:re,detail:"Invalid Stripe API result. Expected customer to contain email address."});c=await Ps({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}`),v.ok(n,e,{title:re,detail:p.message})}if(!c)return v.ok(n,e,{title:re,detail:"No API Key Consumer was created, skipping creation of subscription."});try{let p=fn(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:Qe(t.data.object.trial_end),trialStartDate:Qe(t.data.object.trial_start)}),await Es({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 Is({apiKeyBucketName:r.apiKeyBucketName,consumerId:c,context:e}),v.ok(n,e,{title:re,detail:p.message})}return v.ok(n,e,{title:ze})}s(fo,"onCustomerSubscriptionCreated");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.`),v.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}'`),v.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!==w.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}'.`),v.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.`+Re});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 v.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. `+Re})}return v.ok(n,e,{title:ze})}s(ho,"onCustomerSubscriptionDeleted");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 include '.data.object.id' as the subscription ID.`),v.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}'`),v.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!==w.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}'.`),v.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.`+Re});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=fn(t.data.object.status),l;a.trial_end&&a.trial_end!==t.data.object.trial_end&&t.data.object.trial_end!==null&&(l=Qe(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 v.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. `+Re})}return v.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 gn.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 v.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. `+Re})}return v.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?Qe(t.data.object.cancel_at):null,cancel_at_period_end:t.data.object.cancel_at_period_end,canceled_at:t.data.object.canceled_at?Qe(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 v.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. `+Re})}return v.ok(n,e,{title:ze})}}return e.log.warn(`This update event '${t.id}' is not supported by Stripe monetization plugin webhook.`),v.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."+Re})}s(yo,"onCustomerSubscriptionUpdated");var xs=class extends $t{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(he.ZUPLO_METERING_SERVICE_BUCKET_ID)d=he.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m("StripeMonetizationPlugin - No 'meteringBucketId' property provided");if(!p)if(he.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)p=he.ZUPLO_API_KEY_SERVICE_BUCKET_NAME;else throw new m("StripeMonetizationPlugin - No 'apiKeyBucketName' property provided");if(!w.instance.build.ACCOUNT_NAME)throw new J("Build environment is not configured correctly. Expected 'ACCOUNT_NAME' to be set.");let g=this.options.primaryDataRegion??"us-central1";if(!ju(g))throw new m(`StripeMonetizationPlugin - The value '${g}' on the property 'primaryDataRegion' is invalid.`);let f=await c.json();if(!bs(f))return v.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. "+Re});switch(l.log.info(`Received Stripe webhook event of type '${f.type}' with ID '${f.id}'.`),f.type){case"customer.subscription.created":return await fo(c,l,f,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.updated":return await yo(c,l,f,{meteringBucketId:d,apiKeyBucketName:p,meteringBucketRegion:g,stripeSecretKey:this.options.stripeSecretKey});case"customer.subscription.deleted":return await ho(c,l,f,{meteringBucketId:d});default:return v.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.`+Re})}},"stripeWebhookHandler"),i=Zi({inboundPolicies:[new Ht({signingSecret:this.options.webhooks.signingSecret,tolerance:this.options.webhooks.tolerance},"stripe-webhook-verification")]});ne(this.options.webhooks,"StripeMonetizationPlugin","plugin").required("signingSecret","string").optional("tolerance","number");let a=new ce({processors:[ge,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 ju(n){return n!==null&&typeof n=="string"&&["us-central1","us-east1","europe-west4"].includes(n)}s(ju,"isMetricsRegion");var Ts=new WeakMap,vs={},bo=class{static{s(this,"AmberfloMeteringPolicy")}static setRequestProperties(e,t){Ts.set(e,t)}};async function zu(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=Ts.get(e),u=t.customerId;if(t.customerIdPropertyPath){if(!n.user)throw new N(`Unable to apply customerIdPropertyPath '${t.customerIdPropertyPath}' as request.user is 'undefined'.`);u=Ke(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=vs[t.apiKey];if(!g){let f=t.apiKey,C=n.headers.get("zm-test-id")??"";g=new K("amberflo-ingest-meter",10,async I=>{try{let O=t.url??"https://app.amberflo.io/ingest",U=await F.fetch(O,{method:"POST",body:JSON.stringify(I),headers:{"content-type":"application/json","x-api-key":f,"zm-test-id":C}});U.ok||e.log.error(`Unexpected response in AmberfloMeteringInboundPolicy '${r}'. ${U.status}: ${await U.text()}`)}catch(O){throw e.log.error(`Error in AmberfloMeteringInboundPolicy '${r}': ${O.message}`),O}}),vs[f]=g}g.enqueue(p),e.waitUntil(g.waitUntilFlushed())}}),n}s(zu,"AmberfloMeteringInboundPolicy");async function hn(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(hn,"sha256");var Ss=new Map;async function de(n,e,t){let r,o=`${n}-${e}`,i=Ss.get(o);return i!==void 0?r=i:(r=`zuplo-policy-${await hn(JSON.stringify({policyName:n,options:t}))}`,Ss.set(n,r)),r}s(de,"getPolicyCacheName");var Os="key-metadata-cache-type";function Bu(n,e){return e.authScheme===""?n:n.replace(`${e.authScheme} `,"")}s(Bu,"getKeyValue");async function wo(n,e,t,r){if(h("policy.inbound.api-key"),!t.bucketName)if(he.ZUPLO_API_KEY_SERVICE_BUCKET_NAME)t.bucketName=he.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(O=>o.allowUnauthenticatedRequests?n:v.unauthorized(n,e,{detail:O}),"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=Bu(a,o);if(!u||u==="")return i("No key present");let c=await Vu(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!==Os&&X.getLogger(e).error(`ApiKeyInboundPolicy '${r}' - cached metadata has invalid typeId '${p.typeId}'`,p),i("Authorization Failed");let g={key:u},f=await we({retryDelayMs:5,retries:2,logger:X.getLogger(e)},`${w.instance.apiKeyServiceUrl}/v1/$validate/${o.bucketName}`,{method:"POST",headers:{"content-type":"application/json","zp-rid":e.requestId,"zp-dn":w.instance.deploymentName??"unknown","User-Agent":w.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 O=await f.text(),U=JSON.parse(O);e.log.error("Unexpected response from key service",U)}catch{e.log.error("Invalid response from key service")}throw new N(`ApiKeyInboundPolicy '${r}' - unexpected response from Key Service. Status: ${f.status}`)}let C=await f.json(),I={isValid:!0,typeId:Os,user:{sub:C.name,data:C.metadata}};return n.user=I.user,d.put(c,I,o.cacheTtlSeconds),n}s(wo,"ApiKeyInboundPolicy");async function Vu(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(Vu,"hashValue");var Gu=wo;import{createRemoteJWKSet as Ku,jwtVerify as Cs}from"jose";import{createLocalJWKSet as Wu}from"jose";var Ro=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 Po&&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",w.instance.systemUserAgent),this.options.headers=Object.fromEntries(e.entries())),this.pendingFetch||=this.fetchJwks(this.url,this.timeoutDuration,this.options).then(t=>{this.local=Wu(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 Io("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 As(n,e,t){let r=new Ro(n,e,t);return async(o,i)=>r.getKey(o,i)}s(As,"createRemoteJWKSet");var pt=class extends N{static{s(this,"JWKSError")}},Po=class extends pt{static{s(this,"JWKSNoMatchingKey")}},Io=class extends pt{static{s(this,"JWKSTimeout")}};var yn={},Ju=s((n,e)=>async(t,r)=>{if(!r.jwkUrl||typeof r.jwkUrl!="string")throw new m("Invalid State - jwkUrl not set");if(!yn[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);yn[r.jwkUrl]=As(new URL(r.jwkUrl),u,r.headers?{headers:r.headers}:void 0)}else yn[r.jwkUrl]=Ku(new URL(r.jwkUrl),r.headers?{headers:r.headers}:void 0)}let{payload:o}=await Cs(t,yn[r.jwkUrl],{issuer:r.issuer,audience:r.audience});return o},"createJwkVerifier"),Yu=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"),fe=s(async(n,e,t,r)=>{h("policy.inbound.open-id-jwt-auth");let o=n.headers.get("Authorization"),i="bearer ",a=s(g=>v.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?Ju(r,e):Yu,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 C=new URL(n.url);return"code"in f&&f.code==="ERR_JWT_EXPIRED"?e.log.warn(`Expired token used on url: ${C.pathname} `,f):e.log.warn(`Invalid token on: ${n.method} ${C.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 Qu=s(async(n,e,t,r)=>(h("policy.inbound.auth0-jwt-auth"),fe(n,e,{issuer:`https://${t.auth0Domain}/`,audience:t.audience,jwkUrl:`https://${t.auth0Domain}/.well-known/jwks.json`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"Auth0JwtInboundPolicy");var Xu=[],Eo=class n extends ye{static{s(this,"AxiomaticsAuthZInboundPolicy")}pdpService;static attributeMap;static setXacmlAttributes(e,t){n.attributeMap||(n.attributeMap=new WeakMap),n.attributeMap.set(e,{Request:t})}constructor(e,t){super(e,t),h("policy.inbound.axiomatics-authz"),ne(e,t).required("pdpUrl","string").required("pdpUsername","string").required("pdpPassword","string"),this.pdpService=new Jo(e)}async handler(e,t){let r=s(a=>this.options.allowUnauthorizedRequests?e:v.forbidden(e,t,{detail:a}),"forbiddenResponse");if(e.user===void 0)return t.log.debug("No user found in request. If this is unexpected, check that you have an authentication policy before this one."),this.options.allowUnauthorizedRequests?e:v.unauthorized(e,t);let o=new URL(e.url),i=n.attributeMap?.get(t)??{Request:{}};if(this.options.includeDefaultSubjectAttributes!==!1){let a={Attribute:[{AttributeId:"request.user.sub",Value:e.user.sub}]};i.Request.AccessSubject?i.Request.AccessSubject.push(a):i.Request.AccessSubject=[a]}if(this.options.includeDefaultActionAttributes!==!1){let a={Attribute:[{AttributeId:"request.method",Value:e.method}]};i.Request.Action?i.Request.Action.push(a):i.Request.Action=[a]}if(this.options.includeDefaultResourceAttributes!==!1){let a={Attribute:[{AttributeId:"request.scheme",Value:o.protocol},{AttributeId:"request.host",Value:o.host},{AttributeId:"request.pathname",Value:o.pathname}]};Object.entries(e.params).forEach(([u,c])=>{a.Attribute.push({AttributeId:`request.params.${u}`,Value:c})}),o.searchParams.forEach((u,c)=>{a.Attribute.push({AttributeId:`request.query.${c}`,Value:u})}),i.Request.Action?i.Request.Action.push(a):i.Request.Action=[a]}this.populateAttributes({optionName:"resourceAttributes",authzRequestCategory:"Resource",authzRequest:i,request:e,context:t}),this.populateAttributes({optionName:"actionAttributes",authzRequestCategory:"Action",authzRequest:i,request:e,context:t}),this.populateAttributes({optionName:"accessSubjectAttributes",authzRequestCategory:"AccessSubject",authzRequest:i,request:e,context:t});for(let a of Xu)i=await a(e,t,i);try{let a=await this.pdpService.makePdpRequest(i);return 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),v.internalServerError(e,t)}}populateAttributes({optionName:e,authzRequestCategory:t,authzRequest:r,request:o,context:i}){let a=this.options[e];if(a){let u={Attribute:[]};a.forEach(c=>{let l;if("value"in c)l=c.value;else try{l=ki(o,c.valueSelector)}catch(d){throw d instanceof m?new m(`${this.policyType} '${this.policyName}' - ${d.message}`):new N(`${this.policyType} '${this.policyName}' - ${d.message}`)}l?u.Attribute.push({AttributeId:c.attributeId,Value:l}):i.log.warn(`${this.policyType} '${this.policyName}' - The attribute ${c.attributeId} has no value. If using a selector, check that the selector is correct.`)}),r.Request[t]?r.Request[t].push(u):r.Request[t]=[u]}}};var ec=s(async(n,e,t)=>{h("policy.inbound.basic-auth");let r=n.headers.get("Authorization"),o="basic ",i=s(l=>v.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),C=t.accounts.find(I=>I.username===g&&I.password===f);return C||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 bn(n){return{second:n.getSeconds(),minute:n.getMinutes(),hour:n.getHours(),day:n.getDate(),month:n.getMonth(),weekday:n.getDay(),year:n.getFullYear()}}s(bn,"extractDateElements");function Ls(n,e){return new Date(n,e+1,0).getDate()}s(Ls,"getDaysInMonth");function xo(n,e){return n<=e?e-n:6-n+e+1}s(xo,"getDaysBetweenWeekdays");var wn=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=Ls(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"?xo(d,p):xo(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=bn(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=bn(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}=bn(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 tc={min:0,max:59},nc={min:0,max:59},rc={min:0,max:23},oc={min:1,max:31},ic={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"}},sc={min:0,max:7,aliases:{mon:"1",tue:"2",wed:"3",thu:"4",fri:"5",sat:"6",sun:"7"}},ac={"@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 Xe(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=>{Xe(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(Xe,"parseElement");function vo(n){if(typeof n!="string")throw new TypeError("Invalid cron expression: must be of type string.");n=ac[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 wn({seconds:Xe(t,tc),minutes:Xe(r,nc),hours:Xe(o,rc),days:Xe(i,oc),months:new Set(Array.from(Xe(a,ic)).map(c=>c-1)),weekdays:new Set(Array.from(Xe(u,sc)).map(c=>c%7))})}s(vo,"parseCronExpression");var To=class extends ye{static{s(this,"BrownoutInboundPolicy")}crons;constructor(e,t){if(super(e,t),h("policy.inbound.brownout"),ne(e,t).optional("problem","object"),e.problem&&ne(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=v.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 v.format(i,e,t)}return e}};var uc=["cdn-cache-control","cloudflare-cdn-cache-control","surrogate-control","cache-tag","expires"];async function cc(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(cc,"digestMessage");var lc=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 cc(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 dc(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 lc(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);uc.forEach(C=>f.headers.delete(C)),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(dc,"CachingInboundPolicy");var pc=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 mc=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 gc=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 fc=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",fe(n,e,{issuer:o.href.slice(0,-1),jwkUrl:i.toString(),allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)},"ClerkJwtInboundPolicy");var hc=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 fe(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 yc=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=pe.instance,i=St(t.policies,o?.routeData.policies);return Pr(i)(n,e)},"CompositeInboundPolicy");var bc=s(async(n,e,t,r)=>{h("policy.inbound.curity-phantom-token-auth");let o=n.headers.get("Authorization");if(!o)return v.unauthorized(n,e,{detail:"No authorization header"});let i=wc(o);if(!i)return v.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 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}'`),v.internalServerError(n,e,{detail:"Problem encountered authorizing the HTTP request"})):v.unauthorized(n,e)}return n.headers.set("Authorization",`Bearer ${c}`),n},"CurityPhantomTokenInboundPolicy");function wc(n){return n.split(" ")[0]==="Bearer"?n.split(" ")[1]:null}s(wc,"getToken");var Rc=s(async(n,e,t,r)=>(h("policy.inbound.firebase-jwt-auth"),ne(t,r).required("projectId","string").optional("allowUnauthenticatedRequests","boolean"),fe(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 Pc=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 mt="__unknown__",Ic=s(async(n,e,t,r)=>{h("policy.inbound.geo-filter");let o={allow:{countries:ft(t.allow?.countries,"allow.countries",r),regionCodes:ft(t.allow?.regionCodes,"allow.regionCode",r),asns:ft(t.allow?.asns,"allow.asOrganization",r)},block:{countries:ft(t.block?.countries,"block.countries",r),regionCodes:ft(t.block?.regionCodes,"block.regionCode",r),asns:ft(t.block?.asns,"block.asOrganization",r)},ignoreUnknown:t.ignoreUnknown!==!1},i=e.incomingRequestProperties.country?.toLowerCase()??mt,a=e.incomingRequestProperties.regionCode?.toLowerCase()??mt,u=e.incomingRequestProperties.asn?.toString()??mt,c=o.ignoreUnknown&&i===mt,l=o.ignoreUnknown&&a===mt,d=o.ignoreUnknown&&u===mt,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 gt(n,e,r,i,a,u);let C=o.block.countries,I=o.block.regionCodes,O=o.block.asns;return C.length>0&&C.includes(i)&&!c||I.length>0&&I.includes(a)&&!l||O.length>0&&O.includes(u)&&!d?gt(n,e,r,i,a,u):n},"GeoFilterInboundPolicy");function gt(n,e,t,r,o,i){return e.log.debug(`Request blocked by GeoFilterInboundPolicy '${t}' (country: '${r}', regionCode: '${o}', asn: '${i}')`),v.forbidden(n,e,{geographicContext:{country:r,regionCode:o,asn:i}})}s(gt,"blockedResponse");function ft(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(ft,"toLowerStringArray");var Ec=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 xc=s(async(n,e,t,r)=>{h("policy.inbound.mock-api");let o=e.route.raw().responses;if(!o)return So(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 So(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 ks(a[u])}else return a.length>0?ks(a[0]):So(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 ks(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(ks,"generateResponse");var So=s((n,e,t,r)=>{let o=`Error in policy: ${n} - On route ${e.method} ${t.route.path}. ${r}`;return v.internalServerError(e,t,{detail:o})},"getProblemDetailResponse");var vc="Incoming",Tc={logRequestBody:!0,logResponseBody:!0};function _s(n){let e={};return n.forEach((t,r)=>{e[r]=t}),e}s(_s,"headersToObject");function Ns(){return new Date().toISOString()}s(Ns,"timestamp");var Oo=new WeakMap,Sc={};function Oc(n,e){let t=Oo.get(n);t||(t=Sc);let r=Object.assign({...t},e);Oo.set(n,r)}s(Oc,"setMoesifContext");async function Ds(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(Ds,"readBody");var Ac={},Ao;function Ms(){if(!Ao)throw new N("Invalid State - no _lastLogger");return Ao}s(Ms,"getLastLogger");function Cc(n){let e=Ac[n];return e||(e=new K("moesif-inbound",100,async t=>{let r=JSON.stringify(t);Ms().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||Ms().error({status:o.status,body:await o.text()})})),e}s(Cc,"getDispatcher");async function Lc(n,e,t,r){h("policy.inbound.moesif-analytics"),Ao=e.log;let o=Ns(),i=Object.assign(Tc,t);if(!i.applicationId)throw new Error(`Invalid configuration for MoesifInboundPolicy '${r}' - applicationId is required`);let a=i.logRequestBody?await Ds(n,e):void 0;return e.addResponseSendingFinalHook(async(u,c)=>{let l=Cc(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:_s(n.headers)},f=i.logResponseBody?await Ds(u,e):void 0,C={time:Ns(),status:u.status,headers:_s(u.headers),body:f},I={request:g,response:C,user_id:p.userId??c.user?.sub,session_token:p.sessionToken,company_id:p.companyId,metadata:p.metadata,direction:vc};l.enqueue(I),e.waitUntil(l.waitUntilFlushed())}),n}s(Lc,"MoesifInboundPolicy");async function Hs(n,e,t,r){let o=X.getLogger(n),{authApiJWT:i,meteringServiceUrl:a}=w.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(Hs,"loadSubscription");async function Us(n,e,t,r,o){let{authApiJWT:i,meteringServiceUrl:a}=w.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(Us,"consumeSubcriptionQuotas");var kc=new Set(["active","inactive","incomplete","incomplete-expired","trialing","past-due","canceled","unpaid"]);function Rn(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(Rn,"validateMeters");function Zs(n,e){if(n)try{if(n.length===0)throw new m("Must set valid subscription statuses");let t=Je(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(Zs,"parseAllowedSubscriptionStatuses");function qs(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(qs,"compareMeters");var Co=class extends ye{static{s(this,"MonetizationInboundPolicy")}static getSubscription(e){return Se.get(e,wt)}static setMeters(e,t){Rn(t,"setMeters"),Se.set(e,qt,t)}constructor(e,t){super(e,t),h("policy.inbound.monetization")}async handler(e,t){ne(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=Se.get(t,qt),a={...this.options.meters,...i};Rn(a,this.policyName);let u=this.options.allowRequestsWithoutSubscription??!1,c=Zs(this.options.allowedSubscriptionStatuses,this.policyName);t.addResponseSendingFinalHook(async(I,O,U)=>{let k=Se.get(U,wt);if((this.options.allowRequestsWithoutSubscription??!1)&&!k){U.log.debug(`MonetizationInboundPolicy '${this.policyName}' - No subscription found and property 'allowRequestsWithoutSubscription' is true`);return}if(!this.options.bucketId)if(he.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=he.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let Z=Se.get(U,qt),j={...this.options.meters,...Z};if(Rn(j,this.policyName),o.includes(I.status)&&k&&j){U.log.debug(`MonetizationInboundPolicy '${this.policyName}' - Updating subscription '${k.id}' with meters '${JSON.stringify(j)} on response status '${I.status}'`);let{metersInSubscription:P,metersNotInSubscription:D}=qs(k.meters,j);if(D&&Object.keys(D).length>0){let z=Object.keys(D);U.log.warn(`The following meters cannot be applied since they are not present in the subscription: '${z}'`)}await Us(U,k.id,this.policyName,this.options.bucketId,P)}});let l=e.user;if(!l)return u?e:v.unauthorized(e,t,{detail:"Unable to check subscription for anonymous user"});if(!this.options.bucketId)if(he.ZUPLO_METERING_SERVICE_BUCKET_ID)this.options.bucketId=he.ZUPLO_METERING_SERVICE_BUCKET_ID;else throw new m(`MonetizationInboundPolicy '${this.policyName}' - No bucketId property provided`);let{sub:d}=l,p=await Hs(t,d,this.policyName,this.options.bucketId);if(!p)return t.log.warn("No valid subscription found"),u?e:v.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.`),v.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`),Se.set(t,wt,p));let g=Se.get(t,wt);if(!g)return u?e:(t.log.warn("Subscription is not available for user"),v.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}'`),v.tooManyRequests(e,t,{detail:"Quota is not set up for the user's subscription",title:"Quota Exceeded"});let C=Object.keys(a).filter(I=>!Object.keys(g.meters).includes(I));if(C.length>0)return t.log.warn(`The following policy meters are not present in the subscription: ${C.join(", ")}`),v.tooManyRequests(e,t,{detail:`The following policy meters are not present in the subscription: ${C.join(", ")}`,title:"Quota Exceeded"});for(let I of Object.keys(a))if(g.meters[I].available<=0&&!r)return v.tooManyRequests(e,t,{detail:`Quota exceeded for meter '${I}'`,title:"Quota Exceeded"});return e}};var _c=s(async(n,e,t,r)=>(h("policy.inbound.okta-jwt-auth"),fe(n,e,{issuer:t.issuerUrl,audience:t.audience,jwkUrl:`${t.issuerUrl}/v1/keys`,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests},r)),"OktaJwtInboundPolicy");import{importSPKI as Nc}from"jose";var Lo,Dc=s(async(n,e,t,r)=>{if(h("policy.inbound.propel-auth-jwt-auth"),!Lo)try{Lo=await Nc(t.verifierKey,"RS256")}catch(o){throw e.log.error("Could not import verifier key"),o}return fe(n,e,{issuer:t.authUrl,secret:Lo,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests,subPropertyName:"user_id"},r)},"PropelAuthJwtInboundPolicy");var Bs=et(tt());var $s=et(tt());var Pn=class extends Error{static{s(this,"ValidationError")}constructor(e){super(e)}},ko=class extends Pn{static{s(this,"ArgumentUndefinedError")}constructor(e){super(`The argument '${e}' is undefined.`)}},_o=class extends Pn{static{s(this,"ArgumentTypeError")}constructor(e,t){super(`The argument '${e}' must be of type '${t}'.`)}};function Mc(n,e){if(Ci(n))throw new ko(e)}s(Mc,"throwIfUndefinedOrNull");function Ut(n,e){if(Mc(n,e),!Pe(n))throw new _o(e,"string")}s(Ut,"throwIfNotString");var In=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 Ut(e,"redisClientUrl"),Ut(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}){Ut(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 J("Rate limiting service failed with 401: Unauthorized"):new J(`Rate limiting service failed with (${i.status}): ${typeof a=="string"?a:JSON.stringify(a,null,2)}`)}},En=class{static{s(this,"InMemoryRedisClient")}keyValueStore;constructor(){this.keyValueStore=new Map}isEnabled(){return!0}fetch({url:e,body:t,method:r}){if(Ut(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 J("The in-memory redis client only supports /rate-limit calls")}};var Hc=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"),vn=s(async n=>({key:`ip-${Hc(n)}`}),"getIP"),Tn=s(async n=>({key:`user-${n.user?.sub??"anonymous"}`}),"getUser"),Sn=s(async()=>({key:"all-2d77ce9d-9a3c-4206-9ab2-668cfd271095"}),"getAll"),xn;function On(n,e){let t;if(xn)return xn;if(w.instance.isLocalDevelopment)return e.info("Using in-memory redis client for local development."),t=new En,xn=t,t;let{authApiJWT:r,redisURL:o}=w.instance;if(!Pe(o))throw new J(`RateLimitInboundPolicy '${n}' - rate limit service URL not configured`);if(!Pe(r))throw new J(`RateLimitInboundPolicy '${n}' - service authentication not configured`);if(o&&(t=In.initialize(o,r,w.instance.deploymentName??"unknown",w.instance.systemUserAgent)),!t||!t.isEnabled())throw new J(`RateLimitInboundPolicy '${n}' - no redis ('${t}') or redis.isEnabled ('${t?.isEnabled}) is false`);return xn=t,t}s(On,"getRedisClient");async function An(n,e,t,r,o){let i=Math.floor(e*60);return await t.fetch({url:"/rate-limit",method:"POST",body:JSON.stringify({incrBy:1,expire:i,key:n}),requestId:o})}s(An,"getCountAndUpdateExpiry");function Cn(n,e){let t;if(n.rateLimitBy==="function"){if(!n.identifier)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier must be specified`);if(!n.identifier.module)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.module must be specified`);if(!n.identifier.export)throw new m(`RateLimitInboundPolicy '${e}' - If rateLimitBy set to 'function' options.identifier.export must be specified`);if(t=n.identifier.module[n.identifier.export],!t||typeof t!="function")throw new m(`RateLimitInboundPolicy '${e}' - Custom rate limit function must be a valid function`)}return s(async(o,i,a)=>{let u=await t(o,i,a);if(!u.key){let c=`RateLimitInboundPolicy '${a}' - Custom rate limit function must return a valid key property '${JSON.stringify(u,null,2)}'`;throw i.log.error(c),new N(c)}return u},"outerFunction")}s(Cn,"wrapUserFunction");var Ln="Retry-After";var Fs=(0,$s.debug)("zuplo:policies:RateLimitInboundPolicy"),js=s(async(n,e,t,r)=>{let o=X.getLogger(e),i=s((P,D)=>{let z={};return(!P||P==="retry-after")&&(z[Ln]=D.toString()),v.tooManyRequests(n,e,void 0,z)},"rateLimited"),u={function:Cn(t,r),user:Tn,ip:vn,all:Sn}[t.rateLimitBy],c=await u(n,e,r),l=c.key,d=c.requestsAllowed??t.requestsAllowed,p=c.timeWindowMinutes??t.timeWindowMinutes,g=t.headerMode??"retry-after",f=On(r,o),I=`bucket/${w.instance.build.BUILD_ID}/${r}/${l}`,O=await de(r,void 0,t),U=new ue(O,e),k=An(I,p,f,o,e.requestId),$;s(async()=>{let P=await k;if(P.count>d){let D=Date.now()+P.ttlSeconds*1e3;U.put(I,D,P.ttlSeconds),Fs(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${I}' (async mode)`),$=i(g,P.ttlSeconds)}},"asyncCheck")();let j=await U.get(I);if(j!==void 0&&j>Date.now()){Fs(`RateLimitInboundPolicy '${r}' - returning 429 from cache for '${I}' (async mode)`);let P=Math.round((j-Date.now())/1e3);return i(g,P)}return e.addResponseSendingHook(async P=>$??P),n},"AsyncRateLimitInboundPolicy");var zs=(0,Bs.debug)("zuplo:policies:RateLimitInboundPolicy"),Uc="strict",Vs=s(async(n,e,t,r)=>{if(h("policy.inbound.rate-limit"),(t.mode??Uc)==="async")return js(n,e,t,r);let i=Date.now(),a=X.getLogger(e),u=s((l,d)=>{if(t.throwOnFailure)throw new J(l,{cause:d});a.error(l,d)},"throwOrLog"),c=s((l,d)=>{let p={};return(!l||l==="retry-after")&&(p[Ln]=d.toString()),v.tooManyRequests(n,e,void 0,p)},"rateLimited");try{let d={function:Cn(t,r),user:Tn,ip:vn,all:Sn}[t.rateLimitBy],p=await d(n,e,r),g=p.key,f=p.requestsAllowed??t.requestsAllowed,C=p.timeWindowMinutes??t.timeWindowMinutes,I=t.headerMode??"retry-after",O=On(r,a),k=`bucket/${w.instance.build.BUILD_ID}/${r}/${g}`,$=await An(k,C,O,a,e.requestId);return $.count>f?(zs(`RateLimitInboundPolicy '${r}' - returning 429 from redis for '${k}' (strict mode)`),c(I,$.ttlSeconds)):n}catch(l){return u(l.message,l),n}finally{let l=Date.now()-i;zs(`RateLimitInboundPolicy '${r}' - latency ${l}ms`)}},"RateLimitInboundPolicy");var No;function Gs(n){let e=[];for(let[t,r]of n)e.push({name:t,value:r});return e}s(Gs,"headersToNameValuePairs");function Zc(n){let e=[];return Object.entries(n).forEach(([t,r])=>{e.push({name:t,value:r})}),e}s(Zc,"queryToNameValueParis");function qc(n){if(n===null)return;let e=parseFloat(n);if(!isNaN(e))return e}s(qc,"parseIntOrUndefined");var Ws={};async function Fc(n,e,t,r){h("policy.inbound.readme-metrics");let o=new Date,i=Date.now();return No||(No={name:"zuplo",version:w.instance.build.ZUPLO_VERSION,comment:`zuplo/${w.instance.build.ZUPLO_VERSION}`}),e.addResponseSendingFinalHook(async a=>{try{let u=t.userLabelPropertyPath&&n.user?Ke(n.user,t.userLabelPropertyPath,"userLabelPropertyPath"):n.user?.sub,c=t.userEmailPropertyPath&&n.user?Ke(n.user,t.userEmailPropertyPath,"userEmailPropertyPath"):void 0,l={clientIPAddress:n.headers.get("true-client-ip")??"",development:t.development!==void 0?t.development:w.instance.isWorkingCopy||w.instance.isLocalDevelopment,group:{label:u,email:c,id:n.user?.sub??"anonymous"},request:{log:{creator:No,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:Gs(n.headers),queryString:Zc(n.query)},response:{status:a.status,statusText:a.statusText,headers:Gs(a.headers),content:{size:qc(n.headers.get("content-length"))}}}]}}},d=Ws[t.apiKey];if(!d){let p=t.apiKey;d=new K("readme-metering-inbound-policy",10,async g=>{try{let f=t.url??"https://metrics.readme.io/request",C=await F.fetch(f,{method:"POST",body:JSON.stringify(g),headers:{"content-type":"application/json",authorization:`Basic ${btoa(p+":")}`}});C.status!==202&&e.log.error(`Unexpected response in ReadmeMeteringInboundPolicy '${r}'. ${C.status}: '${await C.text()}'`)}catch(f){throw e.log.error(`Error in ReadmeMeteringInboundPolicy '${r}': '${f.message}'`),f}}),Ws[p]=d}d.enqueue(l),e.waitUntil(d.waitUntilFlushed())}catch(u){e.log.error(u)}}),n}s(Fc,"ReadmeMetricsInboundPolicy");var $c=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 jc=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 zc=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 Bc=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 Ks=s(()=>new Response("Maximum request size exceeded",{status:413,statusText:"Payload Too Large"}),"payloadTooLarge"),Vc=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?Ks():i&&r?n:(await n.clone().text()).length>t.maxSizeInBytes?Ks():n},"RequestSizeLimitInboundPolicy");var ht=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"),yt=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=Mn(t,r,o,c.name),p=pe.instance.schemaValidator[d],g=p(e[c.name]),f=Do(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"),Oe=s((n,e,t,r,o)=>{r?n.log[e](t,r,o):n.log[e](t,o)},"logErrors"),Ae=s(n=>n==="log-only"||n==="reject-and-log","shouldLog"),Ce=s(n=>n==="reject-only"||n==="reject-and-log","shouldReject"),Do=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 Js(n,e,t){if(!t.validateBody||t.validateBody==="none")return;let r;try{r=await e.clone().json()}catch(f){let C=`Error in request body for method : ${e.method} in route: ${n.route.path} with content-type: ${e.headers.get("Content-Type")}`,I=v.badRequest(e,n,{detail:`${C}, see errors property for more details`,errors:`${f}`});if(Ae(t.validateBody)&&Oe(n,t.logLevel??"info",C,[r],f),Ce(t.validateBody))return I}if(!e.headers.get("Content-Type")){let f=`No content-type header defined in incoming request to ${e.method} in route: ${n.route.path}`,C=v.badRequest(e,n,{detail:f});return Ae(t.validateBody)&&Oe(n,t.logLevel??"info",f,[r],[f]),Ce(t.validateBody)?C:void 0}let o=e.headers.get("Content-Type"),i=o.indexOf(";");i>-1&&(o=o.substring(0,i));let a=Hn(n.route.path,e.method,o),u=pe.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")}`,C=v.badRequest(e,n,{detail:f});return Ae(t.validateBody)&&Oe(n,t.logLevel??"info",f,[r],[f]),Ce(t.validateBody)?C:void 0}if(u(r))return;let l=u.errors,d="Request body did not pass validation",p=Do(l),g=v.badRequest(e,n,{detail:`${d}, see errors property for more details`,errors:p});if(Ae(t.validateBody)&&Oe(n,t.logLevel??"info",d,[r],p),Ce(t.validateBody))return g}s(Js,"handleBodyValidation");function Ys(n,e,t){if(!t.validateHeaders||t.validateHeaders==="none")return;let r={};e.headers.forEach((a,u)=>{r[u]=a});let o=ht(n),i=yt(o.filter(a=>a.location==="header"),r,n.route.path,e.method.toLowerCase(),"header");if(!i.isValid){let a="Header validation failed",u=v.badRequest(e,n,{detail:`${a}, see errors property for more details`,errors:i.errors});if(Ae(t.validateHeaders)&&Oe(n,t.logLevel??"info",a,i.invalidValues,i.errors),Ce(t.validateHeaders))return u}}s(Ys,"handleHeadersValidation");function Qs(n,e,t){if(!t.validatePathParameters||t.validatePathParameters==="none")return;let r=ht(n),o=yt(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=v.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Ae(t.validatePathParameters)&&Oe(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ce(t.validatePathParameters))return a}}s(Qs,"handlePathParameterValidation");function Xs(n,e,t){if(!t.validateQueryParameters||t.validateQueryParameters==="none")return;let r=ht(n),o=yt(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=v.badRequest(e,n,{detail:`${i}, see errors property for more details`,errors:o.errors});if(Ae(t.validateQueryParameters)&&Oe(n,t.logLevel??"info",i,o.invalidValues,o.errors),Ce(t.validateQueryParameters))return a}}s(Xs,"handleQueryParameterValidation");var ea=s(async(n,e,t)=>{h("policy.inbound.request-validation");let r=Xs(e,n,t);if(r!==void 0||(r=Qs(e,n,t),r!==void 0)||(r=Ys(e,n,t),r!==void 0))return r;let o=await Js(e,n,t);return o!==void 0?o:n},"RequestValidationInboundPolicy"),Gc=ea;var Wc=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 v.forbidden(n,e,{detail:a})}return n},"RequireOriginInboundPolicy");var Kc=s(async(n,e,t)=>(h("policy.inbound.set-body"),new ee(n,{body:t.body})),"SetBodyInboundPolicy");var Jc=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 Yc=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 Qc=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 Xc=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 el=s(async n=>new Promise(t=>{setTimeout(t,n)}),"sleep"),tl=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 el(t.sleepInMs),n},"SleepInboundPolicy");var nl=s(async(n,e,t,r)=>{h("policy.inbound.supabase-jwt-auth"),ne(t,r).required("secret","string").optional("allowUnauthenticatedRequests","boolean").optional("requiredClaims","object");let o={secret:t.secret,allowUnauthenticatedRequests:t.allowUnauthenticatedRequests??!1},i=await fe(n,e,o,r);if(i instanceof Response)return i;if(!(i instanceof ee))throw new J("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 N(`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?v.unauthorized(n,e,{detail:`Invalid JWT token - missing valid claims ${l.join(", ")}`}):i},"SupabaseJwtInboundPolicy");var rl=s(async(n,e,t,r)=>{h("policy.inbound.upstream-azure-ad-service-auth"),ne(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 ol(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 ol(n,e){let t=new URLSearchParams({client_id:n.activeDirectoryClientId,scope:`${n.activeDirectoryClientId}/.default`,client_secret:n.activeDirectoryClientSecret,grant_type:"client_credentials"}),r=await we({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 N("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 N("Response returned from Azure AD is not in the expected format.")}s(ol,"getAccessToken");var ta="https://accounts.google.com/o/oauth2/token",Mo,il=s(async(n,e,t,r)=>{h("policy.inbound.upstream-firebase-admin-auth"),ne(t,r).required("serviceAccountJson","string"),Mo||(Mo=await Ie.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:Mo,audience:ta,payload:o}),l=await tn(ta,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(!l.access_token)throw new N("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 sl="https://identitytoolkit.googleapis.com/google.identity.identitytoolkit.v1.IdentityToolkit",al=["acr","amr","at_hash","aud","auth_time","azp","cnf","c_hash","exp","iat","iss","jti","nbf","nonce"],Ho,ul=s(async(n,e,t,r)=>{if(h("policy.inbound.upstream-firebase-user-auth"),ne(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(al.indexOf(p)!==-1)throw new m(`Developer claim "${p}" is reserved and cannot be specified.`);o[p]=t.developerClaims[p]}}Ho||(Ho=await Ie.init(t.serviceAccountJson));let i=t.userId;if(!i&&!t.userIdPropertyPath){if(!n.user)throw new N("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 N(`Unable to apply userIdPropertyPath '${t.userIdPropertyPath}' as request.user is 'undefined'. Do you have an authentication policy before this policy?`);i=Ke(n.user,t.userIdPropertyPath,"userIdPropertyPath")}if(!i)throw new N(`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 hn(JSON.stringify(c)),d=await u.get(l);if(!d){let p=await ke({serviceAccount:Ho,audience:sl,payload:c}),g=`https://identitytoolkit.googleapis.com/v1/accounts:signInWithCustomToken?key=${t.webApiKey}`,f=await Ki(g,p,{retries:t.tokenRetries??3,retryDelayMs:10});if(!f.idToken)throw new N("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 Uo,cl=s(async(n,e,t,r)=>{h("policy.inbound.upstream-gcp-jwt"),ne(t,r).required("audience","string").required("serviceAccountJson","string"),Uo||(Uo=await Ie.init(t.serviceAccountJson));let o=await ke({serviceAccount:Uo,audience:t.audience});return n.headers.set("Authorization",`Bearer ${o}`),n},"UpstreamGcpJwtInboundPolicy");var na="https://www.googleapis.com/oauth2/v4/token",Zo,ll=s(async(n,e,t,r)=>{h("policy.inbound.upstream-gcp-service-auth"),ne(t,r).required("serviceAccountJson","string").optional("audience","string").optional("tokenRetries","number").optional("expirationOffsetSeconds","number"),Zo||(Zo=await Ie.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=Je(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:Zo,audience:na,payload:o}),l=await tn(na,c,{retries:t.tokenRetries??3,retryDelayMs:10});if(t.audience){if(!l.id_token)throw new N("Invalid token response from GCP");u=l.id_token}else{if(!l.access_token)throw new N("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 dl=s(async(n,e,t)=>{h("policy.inbound.validate-json-schema");let r=n.clone(),o;try{o=await r.json()}catch{return v.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 J("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 v.badRequest(n,e,{detail:"Incoming body did not pass schema validation",errors:u})},"ValidateJsonSchemaInbound");var ra=s(n=>{var e=Object.defineProperty,t=Object.getOwnPropertyNames,r=s((I,O)=>e(I,"name",{value:O,configurable:!0}),"__name"),o=s((I,O)=>s(function(){return O||(0,I[t(I)[0]])((O={exports:{}}).exports,O),O.exports},"__require"),"__commonJS"),i=o({"node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js"(I){var O={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,$){return $},attributeValueProcessor:function(k,$){return $},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(k,$,Z){return k}},U=r(function(k){return Object.assign({},O,k)},"buildOptions");I.buildOptions=U,I.defaultOptions=O}}),a=o({"node_modules/fast-xml-parser/src/util.js"(I){"use strict";var O=":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",U=O+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040",k="["+O+"]["+U+"]*",$=new RegExp("^"+k+"$"),Z=r(function(P,D){let z=[],G=D.exec(P);for(;G;){let T=[];T.startIndex=D.lastIndex-G[0].length;let x=G.length;for(let H=0;H<x;H++)T.push(G[H]);z.push(T),G=D.exec(P)}return z},"getAllMatches"),j=r(function(P){let D=$.exec(P);return!(D===null||typeof D>"u")},"isName");I.isExist=function(P){return typeof P<"u"},I.isEmptyObject=function(P){return Object.keys(P).length===0},I.merge=function(P,D,z){if(D){let G=Object.keys(D),T=G.length;for(let x=0;x<T;x++)z==="strict"?P[G[x]]=[D[G[x]]]:P[G[x]]=D[G[x]]}},I.getValue=function(P){return I.isExist(P)?P:""},I.isName=j,I.getAllMatches=Z,I.nameRegexp=k}}),u=o({"node_modules/fast-xml-parser/src/xmlparser/xmlNode.js"(I,O){"use strict";var U=class{static{s(this,"XmlNode")}static{r(this,"XmlNode")}constructor(k){this.tagname=k,this.child=[],this[":@"]={}}add(k,$){k==="__proto__"&&(k="#__proto__"),this.child.push({[k]:$})}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})}};O.exports=U}}),c=o({"node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js"(I,O){var U=a();function k(T,x){let H={};if(T[x+3]==="O"&&T[x+4]==="C"&&T[x+5]==="T"&&T[x+6]==="Y"&&T[x+7]==="P"&&T[x+8]==="E"){x=x+9;let se=1,W=!1,Y=!1,xe="";for(;x<T.length;x++)if(T[x]==="<"&&!Y){if(W&&j(T,x))x+=7,[entityName,val,x]=$(T,x+1),val.indexOf("&")===-1&&(H[G(entityName)]={regx:RegExp(`&${entityName};`,"g"),val});else if(W&&P(T,x))x+=8;else if(W&&D(T,x))x+=8;else if(W&&z(T,x))x+=9;else if(Z)Y=!0;else throw new Error("Invalid DOCTYPE");se++,xe=""}else if(T[x]===">"){if(Y?T[x-1]==="-"&&T[x-2]==="-"&&(Y=!1,se--):se--,se===0)break}else T[x]==="["?W=!0:xe+=T[x];if(se!==0)throw new Error("Unclosed DOCTYPE")}else throw new Error("Invalid Tag instead of DOCTYPE");return{entities:H,i:x}}s(k,"readDocType"),r(k,"readDocType");function $(T,x){let H="";for(;x<T.length&&T[x]!=="'"&&T[x]!=='"';x++)H+=T[x];if(H=H.trim(),H.indexOf(" ")!==-1)throw new Error("External entites are not supported");let se=T[x++],W="";for(;x<T.length&&T[x]!==se;x++)W+=T[x];return[H,W,x]}s($,"readEntityExp"),r($,"readEntityExp");function Z(T,x){return T[x+1]==="!"&&T[x+2]==="-"&&T[x+3]==="-"}s(Z,"isComment"),r(Z,"isComment");function j(T,x){return T[x+1]==="!"&&T[x+2]==="E"&&T[x+3]==="N"&&T[x+4]==="T"&&T[x+5]==="I"&&T[x+6]==="T"&&T[x+7]==="Y"}s(j,"isEntity"),r(j,"isEntity");function P(T,x){return T[x+1]==="!"&&T[x+2]==="E"&&T[x+3]==="L"&&T[x+4]==="E"&&T[x+5]==="M"&&T[x+6]==="E"&&T[x+7]==="N"&&T[x+8]==="T"}s(P,"isElement"),r(P,"isElement");function D(T,x){return T[x+1]==="!"&&T[x+2]==="A"&&T[x+3]==="T"&&T[x+4]==="T"&&T[x+5]==="L"&&T[x+6]==="I"&&T[x+7]==="S"&&T[x+8]==="T"}s(D,"isAttlist"),r(D,"isAttlist");function z(T,x){return T[x+1]==="!"&&T[x+2]==="N"&&T[x+3]==="O"&&T[x+4]==="T"&&T[x+5]==="A"&&T[x+6]==="T"&&T[x+7]==="I"&&T[x+8]==="O"&&T[x+9]==="N"}s(z,"isNotation"),r(z,"isNotation");function G(T){if(U.isName(T))return T;throw new Error(`Invalid entity name ${T}`)}s(G,"validateEntityName"),r(G,"validateEntityName"),O.exports=k}}),l=o({"../../node_modules/strnum/strnum.js"(I,O){var U=/^[-+]?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 $={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Z(P,D={}){if(D=Object.assign({},$,D),!P||typeof P!="string")return P;let z=P.trim();if(D.skipLike!==void 0&&D.skipLike.test(z))return P;if(D.hex&&U.test(z))return Number.parseInt(z,16);{let G=k.exec(z);if(G){let T=G[1],x=G[2],H=j(G[3]),se=G[4]||G[6];if(!D.leadingZeros&&x.length>0&&T&&z[2]!==".")return P;if(!D.leadingZeros&&x.length>0&&!T&&z[1]!==".")return P;{let W=Number(z),Y=""+W;return Y.search(/[eE]/)!==-1||se?D.eNotation?W:P:z.indexOf(".")!==-1?Y==="0"&&H===""||Y===H||T&&Y==="-"+H?W:P:x?H===Y||T+H===Y?W:P:z===Y||z===T+Y?W:P}}else return P}}s(Z,"toNumber"),r(Z,"toNumber");function j(P){return P&&P.indexOf(".")!==-1&&(P=P.replace(/0+$/,""),P==="."?P="0":P[0]==="."?P="0"+P:P[P.length-1]==="."&&(P=P.substr(0,P.length-1))),P}s(j,"trimZeros"),r(j,"trimZeros"),O.exports=Z}}),d=o({"node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js"(I,O){"use strict";var U=a(),k=u(),$=c(),Z=l(),j=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:(E,A)=>String.fromCharCode(Number.parseInt(A,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(E,A)=>String.fromCharCode(Number.parseInt(A,16))}},this.addExternalEntities=P,this.parseXml=x,this.parseTextData=D,this.resolveNameSpace=z,this.buildAttributesMap=T,this.isItStopNode=Y,this.replaceEntitiesValue=se,this.readStopNodeData=V,this.saveTextToParentTag=W,this.addChild=H}};function P(R){let E=Object.keys(R);for(let A=0;A<E.length;A++){let B=E[A];this.lastEntities[B]={regex:new RegExp("&"+B+";","g"),val:R[B]}}}s(P,"addExternalEntities"),r(P,"addExternalEntities");function D(R,E,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(E,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 z(R){if(this.options.removeNSPrefix){let E=R.split(":"),A=R.charAt(0)==="/"?"/":"";if(E[0]==="xmlns")return"";E.length===2&&(R=A+E[1])}return R}s(z,"resolveNameSpace"),r(z,"resolveNameSpace");var G=new RegExp(`([^\\s=]+)\\s*(=\\s*(['"])([\\s\\S]*?)\\3)?`,"gm");function T(R,E,A){if(!this.options.ignoreAttributes&&typeof R=="string"){let B=U.getAllMatches(R,G),L=B.length,_={};for(let Q=0;Q<L;Q++){let q=this.resolveNameSpace(B[Q][1]),M=B[Q][4],oe=this.options.attributeNamePrefix+q;if(q.length)if(this.options.transformAttributeName&&(oe=this.options.transformAttributeName(oe)),oe==="__proto__"&&(oe="#__proto__"),M!==void 0){this.options.trimValues&&(M=M.trim()),M=this.replaceEntitiesValue(M);let te=this.options.attributeValueProcessor(q,M,E);te==null?_[oe]=M:typeof te!=typeof M||te!==M?_[oe]=te:_[oe]=ae(M,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(T,"buildAttributesMap"),r(T,"buildAttributesMap");var x=r(function(R){R=R.replace(/\r\n?/g,`
62
+ `);let E=new k("!xml"),A=E,B="",L="";for(let _=0;_<R.length;_++)if(R[_]==="<")if(R[_+1]==="/"){let q=y(R,">",_,"Closing Tag is not closed."),M=R.substring(_+2,q).trim();if(this.options.removeNSPrefix){let Te=M.indexOf(":");Te!==-1&&(M=M.substr(Te+1))}this.options.transformTagName&&(M=this.options.transformTagName(M)),A&&(B=this.saveTextToParentTag(B,A,L));let oe=L.substring(L.lastIndexOf(".")+1);if(M&&this.options.unpairedTags.indexOf(M)!==-1)throw new Error(`Unpaired tag can not be used as closing tag: </${M}>`);let te=0;oe&&this.options.unpairedTags.indexOf(oe)!==-1?(te=L.lastIndexOf(".",L.lastIndexOf(".")-1),this.tagsNodeStack.pop()):te=L.lastIndexOf("."),L=L.substring(0,te),A=this.tagsNodeStack.pop(),B="",_=q}else if(R[_+1]==="?"){let q=S(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 M=new k(q.tagName);M.add(this.options.textNodeName,""),q.tagName!==q.tagExp&&q.attrExpPresent&&(M[":@"]=this.buildAttributesMap(q.tagExp,L,q.tagName)),this.addChild(A,M,L)}_=q.closeIndex+1}else if(R.substr(_+1,3)==="!--"){let q=y(R,"-->",_+4,"Comment is not closed.");if(this.options.commentPropName){let M=R.substring(_+4,q-2);B=this.saveTextToParentTag(B,A,L),A.add(this.options.commentPropName,[{[this.options.textNodeName]:M}])}_=q}else if(R.substr(_+1,2)==="!D"){let q=$(R,_);this.docTypeEntities=q.entities,_=q.i}else if(R.substr(_+1,2)==="!["){let q=y(R,"]]>",_,"CDATA is not closed.")-2,M=R.substring(_+9,q);B=this.saveTextToParentTag(B,A,L);let oe=this.parseTextData(M,A.tagname,L,!0,!1,!0,!0);oe==null&&(oe=""),this.options.cdataPropName?A.add(this.options.cdataPropName,[{[this.options.textNodeName]:M}]):A.add(this.options.textNodeName,oe),_=q+2}else{let q=S(R,_,this.options.removeNSPrefix),M=q.tagName,oe=q.rawTagName,te=q.tagExp,Te=q.attrExpPresent,Go=q.closeIndex;this.options.transformTagName&&(M=this.options.transformTagName(M)),A&&B&&A.tagname!=="!xml"&&(B=this.saveTextToParentTag(B,A,L,!1));let Wo=A;if(Wo&&this.options.unpairedTags.indexOf(Wo.tagname)!==-1&&(A=this.tagsNodeStack.pop(),L=L.substring(0,L.lastIndexOf("."))),M!==E.tagname&&(L+=L?"."+M:M),this.isItStopNode(this.options.stopNodes,L,M)){let ve="";if(te.length>0&&te.lastIndexOf("/")===te.length-1)_=q.closeIndex;else if(this.options.unpairedTags.indexOf(M)!==-1)_=q.closeIndex;else{let Dn=this.readStopNodeData(R,oe,Go+1);if(!Dn)throw new Error(`Unexpected end of ${oe}`);_=Dn.i,ve=Dn.tagContent}let Nn=new k(M);M!==te&&Te&&(Nn[":@"]=this.buildAttributesMap(te,L,M)),ve&&(ve=this.parseTextData(ve,M,L,!0,Te,!0,!0)),L=L.substr(0,L.lastIndexOf(".")),Nn.add(this.options.textNodeName,ve),this.addChild(A,Nn,L)}else{if(te.length>0&&te.lastIndexOf("/")===te.length-1){M[M.length-1]==="/"?(M=M.substr(0,M.length-1),L=L.substr(0,L.length-1),te=M):te=te.substr(0,te.length-1),this.options.transformTagName&&(M=this.options.transformTagName(M));let ve=new k(M);M!==te&&Te&&(ve[":@"]=this.buildAttributesMap(te,L,M)),this.addChild(A,ve,L),L=L.substr(0,L.lastIndexOf("."))}else{let ve=new k(M);this.tagsNodeStack.push(A),M!==te&&Te&&(ve[":@"]=this.buildAttributesMap(te,L,M)),this.addChild(A,ve,L),A=ve}B="",_=Go}}else B+=R[_];return E.child},"parseXml");function H(R,E,A){let B=this.options.updateTag(E.tagname,A,E[":@"]);B===!1||(typeof B=="string"&&(E.tagname=B),R.addChild(E))}s(H,"addChild"),r(H,"addChild");var se=r(function(R){if(this.options.processEntities){for(let E in this.docTypeEntities){let A=this.docTypeEntities[E];R=R.replace(A.regx,A.val)}for(let E in this.lastEntities){let A=this.lastEntities[E];R=R.replace(A.regex,A.val)}if(this.options.htmlEntities)for(let E in this.htmlEntities){let A=this.htmlEntities[E];R=R.replace(A.regex,A.val)}R=R.replace(this.ampEntity.regex,this.ampEntity.val)}return R},"replaceEntitiesValue");function W(R,E,A,B){return R&&(B===void 0&&(B=Object.keys(E.child).length===0),R=this.parseTextData(R,E.tagname,A,!1,E[":@"]?Object.keys(E[":@"]).length!==0:!1,B),R!==void 0&&R!==""&&E.add(this.options.textNodeName,R),R=""),R}s(W,"saveTextToParentTag"),r(W,"saveTextToParentTag");function Y(R,E,A){let B="*."+A;for(let L in R){let _=R[L];if(B===_||E===_)return!0}return!1}s(Y,"isItStopNode"),r(Y,"isItStopNode");function xe(R,E,A=">"){let B,L="";for(let _=E;_<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(xe,"tagExpWithClosingIndex"),r(xe,"tagExpWithClosingIndex");function y(R,E,A,B){let L=R.indexOf(E,A);if(L===-1)throw new Error(B);return L+E.length-1}s(y,"findClosingIndex"),r(y,"findClosingIndex");function S(R,E,A,B=">"){let L=xe(R,E+1,B);if(!L)return;let _=L.data,Q=L.index,q=_.search(/\s/),M=_,oe=!0;q!==-1&&(M=_.substring(0,q),_=_.substring(q+1).trimStart());let te=M;if(A){let Te=M.indexOf(":");Te!==-1&&(M=M.substr(Te+1),oe=M!==L.data.substr(Te+1))}return{tagName:M,tagExp:_,closeIndex:Q,attrExpPresent:oe,rawTagName:te}}s(S,"readTagExp"),r(S,"readTagExp");function V(R,E,A){let B=A,L=1;for(;A<R.length;A++)if(R[A]==="<")if(R[A+1]==="/"){let _=y(R,">",A,`${E} is not closed`);if(R.substring(A+2,_).trim()===E&&(L--,L===0))return{tagContent:R.substring(B,A),i:_};A=_}else if(R[A+1]==="?")A=y(R,"?>",A+1,"StopNode is not closed.");else if(R.substr(A+1,3)==="!--")A=y(R,"-->",A+3,"StopNode is not closed.");else if(R.substr(A+1,2)==="![")A=y(R,"]]>",A,"StopNode is not closed.")-2;else{let _=S(R,A,">");_&&((_&&_.tagName)===E&&_.tagExp[_.tagExp.length-1]!=="/"&&L++,A=_.closeIndex)}}s(V,"readStopNodeData"),r(V,"readStopNodeData");function ae(R,E,A){if(E&&typeof R=="string"){let B=R.trim();return B==="true"?!0:B==="false"?!1:Z(R,A)}else return U.isExist(R)?R:""}s(ae,"parseValue"),r(ae,"parseValue"),O.exports=j}}),p=o({"node_modules/fast-xml-parser/src/xmlparser/node2json.js"(I){"use strict";function O(j,P){return U(j,P)}s(O,"prettify"),r(O,"prettify");function U(j,P,D){let z,G={};for(let T=0;T<j.length;T++){let x=j[T],H=k(x),se="";if(D===void 0?se=H:se=D+"."+H,H===P.textNodeName)z===void 0?z=x[H]:z+=""+x[H];else{if(H===void 0)continue;if(x[H]){let W=U(x[H],P,se),Y=Z(W,P);x[":@"]?$(W,x[":@"],se,P):Object.keys(W).length===1&&W[P.textNodeName]!==void 0&&!P.alwaysCreateTextNode?W=W[P.textNodeName]:Object.keys(W).length===0&&(P.alwaysCreateTextNode?W[P.textNodeName]="":W=""),G[H]!==void 0&&G.hasOwnProperty(H)?(Array.isArray(G[H])||(G[H]=[G[H]]),G[H].push(W)):P.isArray(H,se,Y)?G[H]=[W]:G[H]=W}}}return typeof z=="string"?z.length>0&&(G[P.textNodeName]=z):z!==void 0&&(G[P.textNodeName]=z),G}s(U,"compress"),r(U,"compress");function k(j){let P=Object.keys(j);for(let D=0;D<P.length;D++){let z=P[D];if(z!==":@")return z}}s(k,"propName"),r(k,"propName");function $(j,P,D,z){if(P){let G=Object.keys(P),T=G.length;for(let x=0;x<T;x++){let H=G[x];z.isArray(H,D+"."+H,!0,!0)?j[H]=[P[H]]:j[H]=P[H]}}}s($,"assignAttributes"),r($,"assignAttributes");function Z(j,P){let{textNodeName:D}=P,z=Object.keys(j).length;return!!(z===0||z===1&&(j[D]||typeof j[D]=="boolean"||j[D]===0))}s(Z,"isLeafTag"),r(Z,"isLeafTag"),I.prettify=O}}),g=o({"node_modules/fast-xml-parser/src/validator.js"(I){"use strict";var O=a(),U={allowBooleanAttributes:!1,unpairedTags:[]};I.validate=function(y,S){S=Object.assign({},U,S);let V=[],ae=!1,R=!1;y[0]==="\uFEFF"&&(y=y.substr(1));for(let E=0;E<y.length;E++)if(y[E]==="<"&&y[E+1]==="?"){if(E+=2,E=$(y,E),E.err)return E}else if(y[E]==="<"){let A=E;if(E++,y[E]==="!"){E=Z(y,E);continue}else{let B=!1;y[E]==="/"&&(B=!0,E++);let L="";for(;E<y.length&&y[E]!==">"&&y[E]!==" "&&y[E]!==" "&&y[E]!==`
63
+ `&&y[E]!=="\r";E++)L+=y[E];if(L=L.trim(),L[L.length-1]==="/"&&(L=L.substring(0,L.length-1),E--),!W(L)){let q;return L.trim().length===0?q="Invalid space after '<'.":q="Tag '"+L+"' is an invalid name.",H("InvalidTag",q,Y(y,E))}let _=D(y,E);if(_===!1)return H("InvalidAttr","Attributes for '"+L+"' have open quote.",Y(y,E));let Q=_.value;if(E=_.index,Q[Q.length-1]==="/"){let q=E-Q.length;Q=Q.substring(0,Q.length-1);let M=G(Q,S);if(M===!0)ae=!0;else return H(M.err.code,M.err.msg,Y(y,q+M.err.line))}else if(B)if(_.tagClosed){if(Q.trim().length>0)return H("InvalidTag","Closing tag '"+L+"' can't have attributes or invalid starting.",Y(y,A));{let q=V.pop();if(L!==q.tagName){let M=Y(y,q.tagStartPos);return H("InvalidTag","Expected closing tag '"+q.tagName+"' (opened in line "+M.line+", col "+M.col+") instead of closing tag '"+L+"'.",Y(y,A))}V.length==0&&(R=!0)}}else return H("InvalidTag","Closing tag '"+L+"' doesn't have proper closing.",Y(y,E));else{let q=G(Q,S);if(q!==!0)return H(q.err.code,q.err.msg,Y(y,E-Q.length+q.err.line));if(R===!0)return H("InvalidXml","Multiple possible root nodes found.",Y(y,E));S.unpairedTags.indexOf(L)!==-1||V.push({tagName:L,tagStartPos:A}),ae=!0}for(E++;E<y.length;E++)if(y[E]==="<")if(y[E+1]==="!"){E++,E=Z(y,E);continue}else if(y[E+1]==="?"){if(E=$(y,++E),E.err)return E}else break;else if(y[E]==="&"){let q=x(y,E);if(q==-1)return H("InvalidChar","char '&' is not expected.",Y(y,E));E=q}else if(R===!0&&!k(y[E]))return H("InvalidXml","Extra text at the end",Y(y,E));y[E]==="<"&&E--}}else{if(k(y[E]))continue;return H("InvalidChar","char '"+y[E]+"' is not expected.",Y(y,E))}if(ae){if(V.length==1)return H("InvalidTag","Unclosed tag '"+V[0].tagName+"'.",Y(y,V[0].tagStartPos));if(V.length>0)return H("InvalidXml","Invalid '"+JSON.stringify(V.map(E=>E.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return H("InvalidXml","Start tag expected.",1);return!0};function k(y){return y===" "||y===" "||y===`
64
+ `||y==="\r"}s(k,"isWhiteSpace"),r(k,"isWhiteSpace");function $(y,S){let V=S;for(;S<y.length;S++)if(y[S]=="?"||y[S]==" "){let ae=y.substr(V,S-V);if(S>5&&ae==="xml")return H("InvalidXml","XML declaration allowed only at the start of the document.",Y(y,S));if(y[S]=="?"&&y[S+1]==">"){S++;break}else continue}return S}s($,"readPI"),r($,"readPI");function Z(y,S){if(y.length>S+5&&y[S+1]==="-"&&y[S+2]==="-"){for(S+=3;S<y.length;S++)if(y[S]==="-"&&y[S+1]==="-"&&y[S+2]===">"){S+=2;break}}else if(y.length>S+8&&y[S+1]==="D"&&y[S+2]==="O"&&y[S+3]==="C"&&y[S+4]==="T"&&y[S+5]==="Y"&&y[S+6]==="P"&&y[S+7]==="E"){let V=1;for(S+=8;S<y.length;S++)if(y[S]==="<")V++;else if(y[S]===">"&&(V--,V===0))break}else if(y.length>S+9&&y[S+1]==="["&&y[S+2]==="C"&&y[S+3]==="D"&&y[S+4]==="A"&&y[S+5]==="T"&&y[S+6]==="A"&&y[S+7]==="["){for(S+=8;S<y.length;S++)if(y[S]==="]"&&y[S+1]==="]"&&y[S+2]===">"){S+=2;break}}return S}s(Z,"readCommentAndCDATA"),r(Z,"readCommentAndCDATA");var j='"',P="'";function D(y,S){let V="",ae="",R=!1;for(;S<y.length;S++){if(y[S]===j||y[S]===P)ae===""?ae=y[S]:ae!==y[S]||(ae="");else if(y[S]===">"&&ae===""){R=!0;break}V+=y[S]}return ae!==""?!1:{value:V,index:S,tagClosed:R}}s(D,"readAttributeStr"),r(D,"readAttributeStr");var z=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function G(y,S){let V=O.getAllMatches(y,z),ae={};for(let R=0;R<V.length;R++){if(V[R][1].length===0)return H("InvalidAttr","Attribute '"+V[R][2]+"' has no space in starting.",xe(V[R]));if(V[R][3]!==void 0&&V[R][4]===void 0)return H("InvalidAttr","Attribute '"+V[R][2]+"' is without value.",xe(V[R]));if(V[R][3]===void 0&&!S.allowBooleanAttributes)return H("InvalidAttr","boolean attribute '"+V[R][2]+"' is not allowed.",xe(V[R]));let E=V[R][2];if(!se(E))return H("InvalidAttr","Attribute '"+E+"' is an invalid name.",xe(V[R]));if(!ae.hasOwnProperty(E))ae[E]=1;else return H("InvalidAttr","Attribute '"+E+"' is repeated.",xe(V[R]))}return!0}s(G,"validateAttributeString"),r(G,"validateAttributeString");function T(y,S){let V=/\d/;for(y[S]==="x"&&(S++,V=/[\da-fA-F]/);S<y.length;S++){if(y[S]===";")return S;if(!y[S].match(V))break}return-1}s(T,"validateNumberAmpersand"),r(T,"validateNumberAmpersand");function x(y,S){if(S++,y[S]===";")return-1;if(y[S]==="#")return S++,T(y,S);let V=0;for(;S<y.length;S++,V++)if(!(y[S].match(/\w/)&&V<20)){if(y[S]===";")break;return-1}return S}s(x,"validateAmpersand"),r(x,"validateAmpersand");function H(y,S,V){return{err:{code:y,msg:S,line:V.line||V,col:V.col}}}s(H,"getErrorObject"),r(H,"getErrorObject");function se(y){return O.isName(y)}s(se,"validateAttrName"),r(se,"validateAttrName");function W(y){return O.isName(y)}s(W,"validateTagName"),r(W,"validateTagName");function Y(y,S){let V=y.substring(0,S).split(/\r?\n/);return{line:V.length,col:V[V.length-1].length+1}}s(Y,"getLineNumberForPosition"),r(Y,"getLineNumberForPosition");function xe(y){return y.startIndex+y[1].length}s(xe,"getPositionFromMatch"),r(xe,"getPositionFromMatch")}}),f=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(I,O){var{buildOptions:U}=i(),k=d(),{prettify:$}=p(),Z=g(),j=class{static{s(this,"XMLParser")}static{r(this,"XMLParser")}constructor(P){this.externalEntities={},this.options=U(P)}parse(P,D){if(typeof P!="string")if(P.toString)P=P.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(D){D===!0&&(D={});let T=Z.validate(P,D);if(T!==!0)throw Error(`${T.err.msg}:${T.err.line}:${T.err.col}`)}let z=new k(this.options);z.addExternalEntities(this.externalEntities);let G=z.parseXml(P);return this.options.preserveOrder||G===void 0?G:$(G,this.options)}addEntity(P,D){if(D.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(P.indexOf("&")!==-1||P.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[P]=D}};O.exports=j}});let C=f();return new C(n)},"getXmlParser");var qo=class extends Fe{static{s(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),h("policy.outbound.xml-to-json"),ne(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=ra({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 N(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 Fo=class{static{s(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new J(`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 $o=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 K(t.name??"",t.msDelay,e)}enqueue=e=>{this.#e.enqueue(e),ln().waitUntil(this.#e.waitUntilFlushed())}};var oa=10,ia=3e4,jo=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=ia,this.#r=oa}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:ia,this.#r=oa}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 pl(()=>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);ln().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 pl(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(pl,"waitUntilTrue");var zo=["sha-1","sha-256","sha-384","sha-512"],kn=class{static{s(this,"BaseCryptoBeta")}};var Bo=class extends kn{static{s(this,"WorkerCryptoBeta")}async digest(e,t){if(!zo.includes(e.toLowerCase()))throw new N(`Algorithm ${e} is not supported. Try using ${zo.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 _n=class{constructor(e){this.context=e}static{s(this,"BaseKeyValueStore")}};var Vo=class extends _n{static{s(this,"WorkerKeyValueStore")}#e;constructor(e){super(e);let t=w.instance.runtime.ZUPLO_KV;if(!t)throw new Ko("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{Qr as AWSLoggingPlugin,zu as AmberfloMeteringInboundPolicy,bo as AmberfloMeteringPolicy,Gu as ApiAuthKeyInboundPolicy,wo as ApiKeyInboundPolicy,uo as AuditLogDataStaxProvider,co as AuditLogPlugin,Qu as Auth0JwtInboundPolicy,lu as AwsLambdaHandlerExtensions,Eo as AxiomaticsAuthZInboundPolicy,$o as BackgroundDispatcher,jo as BackgroundLoader,ec as BasicAuthInboundPolicy,Vs as BasicRateLimitInboundPolicy,K as BatchDispatch,To as BrownoutInboundPolicy,dc as CachingInboundPolicy,pc as ChangeMethodInboundPolicy,mc as ClearHeadersInboundPolicy,gc as ClearHeadersOutboundPolicy,fc as ClerkJwtInboundPolicy,hc as CognitoJwtInboundPolicy,yc as CompositeInboundPolicy,m as ConfigurationError,ir as ContentTypes,Se as ContextData,Bo as CryptoBeta,bc as CurityPhantomTokenInboundPolicy,Cr as DataDogLoggingPlugin,to as DataDogMetricsPlugin,jr as DynaTraceLoggingPlugin,io as DynatraceMetricsPlugin,Rc as FirebaseJwtInboundPolicy,Pc as FormDataToJsonInboundPolicy,Ic as GeoFilterInboundPolicy,vr as GoogleCloudLoggingPlugin,Dr as Handler,v as HttpProblems,Vt as HttpStatusCode,ye as InboundPolicy,Ec as JWTScopeValidationInboundPolicy,Vo as KeyValueStore,Br as LokiLoggingPlugin,Nt as LookupResult,ue as MemoryZoneReadThroughCache,xc as MockApiInboundPolicy,Lc as MoesifInboundPolicy,Co as MonetizationInboundPolicy,_c as OktaJwtInboundPolicy,fe as OpenIdJwtInboundPolicy,Fe as OutboundPolicy,Ge as ProblemResponseFormatter,Dc as PropelAuthJwtInboundPolicy,Vs as RateLimitInboundPolicy,Fc as ReadmeMetricsInboundPolicy,$c as RemoveHeadersInboundPolicy,jc as RemoveHeadersOutboundPolicy,zc as RemoveQueryParamsInboundPolicy,Bc as ReplaceStringOutboundPolicy,Vc as RequestSizeLimitInboundPolicy,ea as RequestValidationInboundPolicy,Wc as RequireOriginInboundPolicy,Et as ResponseSendingEvent,xt as ResponseSentEvent,Dt as Router,N as RuntimeError,Ft as SYSTEM_LOGGER,Gc as SchemaBasedRequestValidation,Le as SemanticAttributes,Fo as ServiceProviderImpl,Kc as SetBodyInboundPolicy,Jc as SetHeadersInboundPolicy,Yc as SetHeadersOutboundPolicy,Qc as SetQueryParamsInboundPolicy,Xc as SetStatusOutboundPolicy,tl as SleepInboundPolicy,xs as StripeMonetizationPlugin,Ht as StripeWebhookVerificationInboundPolicy,Wr as SumoLogicLoggingPlugin,nl as SupabaseJwtInboundPolicy,Ue as SystemRouteName,Rt as TelemetryPlugin,rl as UpstreamAzureAdServiceAuthInboundPolicy,il as UpstreamFirebaseAdminAuthInboundPolicy,ul as UpstreamFirebaseUserAuthInboundPolicy,cl as UpstreamGcpJwtInboundPolicy,ll as UpstreamGcpServiceAuthInboundPolicy,Jr as VMWareLogInsightLoggingPlugin,dl as ValidateJsonSchemaInbound,qo as XmlToJsonOutboundPolicy,bt as ZoneCache,ee as ZuploRequest,du as awsLambdaHandler,he as environment,Mn as getIdForParameterSchema,aa as getIdForRefSchema,Hn as getIdForRequestBodySchema,sa as getRawOperationDataIdentifierName,ar as httpStatuses,wu as openApiSpecHandler,Pu as redirectHandler,ua as sanitizedIdentifierName,sr as serialize,Oc as setMoesifContext,h as trackFeature,Eu as urlForwardHandler,vu as urlRewriteHandler,Tu as webSocketHandler,Su as webSocketPipelineHandler};
65
65
  /*! For license information please see index.js.LEGAL.txt */