@zuplo/graphql 5.1647.0 → 5.1648.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/index.minified.js CHANGED
@@ -32,7 +32,7 @@
32
32
  `))):c=e.stylize("[Circular]","special")),yh(a)){if(s&&i.match(/^\d+$/))return c;a=JSON.stringify(""+i),a.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(a=a.substr(1,a.length-2),a=e.stylize(a,"name")):(a=a.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),a=e.stylize(a,"string"))}return a+": "+c}o(pu,"formatProperty");function iw(e,t){if(yh(t))return e.stylize("undefined","undefined");if(gh(t)){let r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(tw(t))return e.stylize(""+t,"number");if(XE(t))return e.stylize(""+t,"boolean");if(bh(t))return e.stylize("null","null")}o(iw,"formatPrimitive");function ow(e,t,r){let n=0;return e.reduce(function(s,a){return n++,a.indexOf(`
33
33
  `)>=0&&n++,s+a.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?r[0]+(t===""?"":t+`
34
34
  `)+" "+e.join(`,
35
- `)+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}o(ow,"reduceToSingleString")});var wh=g(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.format=void 0;var sw=fh(),aw=Eh(),cw=o((e,...t)=>(0,sw.format)(aw.inspect,e,t),"format");so.format=cw});var Sr=g(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.debug=Jt.withoutEnv=Jt.Debugger=void 0;var uw=hh(),lw=wh(),ao=class{static{o(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,r){this.manager=t,this.ns=r,this.color=(0,uw.generateColor)(r),this.last=0,this.enabled=t.enabled.some(n=>n.test(r))}log(...t){if(!this.enabled)return;let r,n=t[0];typeof n=="function"?r=n():r=String(n);let i=Date.now()-(this.last||Date.now());r=(0,lw.format)(r,...t);let s=`${this.color(this.ns)} ${r} ${this.color(`+${i}ms`)}`;console.log(s),this.last=Date.now()}};Jt.Debugger=ao;var co=class{static{o(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function vh(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}o(vh,"extract");var Xn;function dw(e){e||(e=[]),typeof e=="string"&&(e=vh(e)),Xn=new co(e)}o(dw,"withoutEnv");Jt.withoutEnv=dw;function pw(e){let t=globalThis.DEBUG;Xn||(Xn=new co(vh(t)));let r=new ao(Xn,e);return Xn.debuggers.set(e,r),Object.assign(r.log.bind(r),{self:r})}o(pw,"debug");Jt.debug=pw});var lo=g(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.ProblemResponseFormatter=Kr.InternalProblemResponseFormatter=void 0;var hw=D(),uo=class e{static{o(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async t=>{let r=t.problem,n=JSON.stringify(r,null,2);return new Response(n,{status:t.problem.status,statusText:t.statusText,headers:{...t.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(t){t&&(e.problemResponseFormat=(r,n,i)=>{try{return t(r,n,i)}catch(s){throw new hw.RuntimeError("Error in custom 'problemResponseFormat'",{cause:s})}})}};Kr.InternalProblemResponseFormatter=uo;var mu=class{static{o(this,"ProblemResponseFormatter")}static async format(t,r,n){return await uo.problemResponseFormat(t,r,n)}};Kr.ProblemResponseFormatter=mu});var xt=g(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.initializeRuntime=be.invokeOnResponseSendingFinalExtensions=be.invokeOnResponseSendingExtensions=be.invokeOnRequestExtensions=be.plugins=be.runtimeExtensions=be.InitializableRuntimePlugin=be.RuntimePlugin=void 0;var fw=lo(),ho=class{static{o(this,"RuntimePlugin")}};be.RuntimePlugin=ho;var fo=class extends ho{static{o(this,"InitializableRuntimePlugin")}};be.InitializableRuntimePlugin=fo;be.runtimeExtensions={};var yu=[];be.plugins=yu;var Th=[],Sh=[],Ih=[],po={addPlugin(e){yu.push(e)},addRequestHook(e){Th.push(e)},addResponseSendingHook(e){Sh.push(e)},addResponseSendingFinalHook(e){Ih.push(e)}},mw=o(async(e,t)=>{let r=e;for(let n of Th)if(r=await n(r,t),r instanceof Response)return r;return r},"invokeOnRequestExtensions");be.invokeOnRequestExtensions=mw;var yw=o(async(e,t,r)=>{let n=e;for(let i of Sh)n=await i(e,t,r);return n},"invokeOnResponseSendingExtensions");be.invokeOnResponseSendingExtensions=yw;var gw=o(async(e,t,r)=>{for(let n of Ih)await n(e,t,r)},"invokeOnResponseSendingFinalExtensions");be.invokeOnResponseSendingFinalExtensions=gw;async function bw(e=()=>Promise.resolve()){await e(po),be.runtimeExtensions.value=po;let t=yu.filter(r=>r instanceof fo);for(let r of t)await r.initialize(po);fw.InternalProblemResponseFormatter.setProblemResponseFormat(po.problemResponseFormat)}o(bw,"initializeRuntime");be.initializeRuntime=bw});var gu=g(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.serialize=zt.ContentTypes=void 0;zt.ContentTypes={Json:"application/json",Form:"application/x-www-form-urlencoded"};function _w(e,t){if(e!==null)return t&&typeof e=="string"?e:typeof e=="object"&&t?.startsWith(zt.ContentTypes.Form)?new URLSearchParams(e).toString():typeof e=="object"&&t?.startsWith(zt.ContentTypes.Json)||!t?JSON.stringify(e):e}o(_w,"serialize");zt.serialize=_w});var Wt=g(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.Pipeline=void 0;var bu=Ir(),Ah=xt(),Ew=gu(),_u=class{static{o(this,"Pipeline")}constructor(t,r,n){this.execute=this.#t(t,r,n)}execute;#e=(t,r)=>async(n,i)=>{try{return await t(n,i)}catch(s){return i.log.error("Error executing request handler.",s),r.errorHandler(n,i,s)}};#t=(t,r,n)=>async(i,s)=>{let a=[...t],c=o(async m=>{let v=a.pop();return v?v(i,s,n,c):await this.#e(async S=>{let O=await r(S,s);return ww(O)},n)(m,s)},"nextPipe"),l=await c(i),d=new bu.ResponseSendingEvent(i,l);s.dispatchEvent(d);let p=bu.ZuploContextExtensions.getContextExtensions(s),y=p.latestRequest,h;try{h=await d.mutableResponse}catch(m){return s.log.error(m),n.errorHandler(i,s,m)}try{h=await p.onResponseSending(h,y,s)}catch(m){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${m.message}'`,m),n.errorHandler(i,s,m)}try{h=await(0,Ah.invokeOnResponseSendingExtensions)(h,y,s)}catch(m){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${m.message}'`,m),n.errorHandler(i,s,m)}s.dispatchEvent(new bu.ResponseSentEvent(i,h));try{await p.onResponseSendingFinal(l,y,s)}catch(m){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${m.message}'`,m),m}try{await(0,Ah.invokeOnResponseSendingFinalExtensions)(l,y,s)}catch(m){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${m.message}'`,m),m}return h}};mo.Pipeline=_u;function ww(e){return e instanceof Response?e:typeof e>"u"?new Response:new Response((0,Ew.serialize)(e),{headers:{"content-type":"application/json"}})}o(ww,"resultToResponse")});var go=g(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.MetricsPlugin=void 0;var vw=xt(),Eu=class extends vw.RuntimePlugin{static{o(this,"MetricsPlugin")}};yo.MetricsPlugin=Eu});var Ke=g(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.SystemLogMap=void 0;var Tw=D(),wu=class e{static{o(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(t){let r=e.#e.get(t);if(!r){let n=`No system logger found for context with requestId '${t.requestId}'`;throw console.error(n),new Tw.SystemError(n)}return r}static addLogger(t,r){e.#e.set(t,r)}};bo.SystemLogMap=wu});var Se=g(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.BatchDispatch=void 0;var vu=class{static{o(this,"BatchDispatch")}constructor(t,r,n,i){this.#t=t,this.#o=r,this.#n=n,this.#r=i}#e=void 0;#t;#r;#n;#i=[];#o;enqueue=t=>{this.#i.push(t),this.#e||(this.#e=new Promise(r=>{setTimeout(()=>{if(this.#i.length>0){let n=[...this.#i];this.#i.length=0,this.#e=void 0,this.#n(n).catch(i=>{this.#r&&this.#r.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,i.message,i.stack)}).finally(()=>{r()})}},this.#o)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};_o.BatchDispatch=vu});var Ph=g(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.EllieMetricsTransport=void 0;var Rh=Ke(),Sw=Se(),Eo=ee(),Tu=class{static{o(this,"EllieMetricsTransport")}#e;#t;#r;constructor(t){this.#r=Eo.Environment.instance.loggingId,this.#e=t,this.#t=new Sw.BatchDispatch("ellie-metrics-transport",10,this.dispatchFunction,Rh.SystemLogMap.getLogger(t))}pushMetrics(t,r){this.#r!==void 0&&(this.#t.enqueue(t),r.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async t=>{if(t.length===0)return;let r,{loggingId:n,remoteLogURL:i,deploymentName:s}=Eo.Environment.instance,a=t.map(c=>{let u=Object.assign({},c);return delete u.requestContentLength,delete u.responseContentLength,u});if(n&&s&&(r=`${i}/v1-alpha/metrics?loggingId=${encodeURI(n)}&deploymentName=${encodeURI(s)}`),r){let c=await fetch(r,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":Eo.Environment.instance.deploymentName??"unknown","user-agent":Eo.Environment.instance.systemUserAgent}});if(!c.ok){let u=await c.text();Rh.SystemLogMap.getLogger(this.#e).error(`Metrics POST responded ${c.status}: ${c.statusText}`,u)}}}};wo.EllieMetricsTransport=Tu});var mt=g(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.systemNoVersion=Ar.SystemRouteConfiguration=void 0;var Su=class{static{o(this,"SystemRouteConfiguration")}constructor({label:t,path:r,methods:n,systemRouteName:i,corsPolicy:s="none"}){this.label=t,this.path=r,this.methods=n,this.corsPolicy=s,this.version=Ar.systemNoVersion.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=i}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}};Ar.SystemRouteConfiguration=Su;Ar.systemNoVersion={name:"__system-no-version",pathPrefix:""}});var Rr=g(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.metricsProcessor=void 0;var Oh=Zn(),Iw=Ir(),Aw=xt(),Rw=go(),Pw=Ph(),Ow=mt(),Nw=o(async(e,t,r,n)=>{let i=new Date,s=Date.now(),a=await n(e),c=e.headers.get(Oh.RAY_ID_HEADER)??void 0,u=e.headers.get(Oh.TRUE_CLIENT_IP)??void 0,l=t.incomingRequestProperties,d;t.route instanceof Ow.SystemRouteConfiguration&&(d=t.route.systemRouteName);let p=Iw.ZuploContextExtensions.getContextExtensions(t).latestRequest,y={timestamp:i,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:e.headers.get("content-length")?Number(e.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:t.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:t.requestId,method:e.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:c,instanceId:r.instanceId,userSub:p.user?.sub,clientIp:u},h=[];return h.push(new Pw.EllieMetricsTransport(t)),Aw.plugins.forEach(m=>{if(m instanceof Rw.MetricsPlugin){let v=m.getTransport();h.push(v)}}),h.forEach(m=>{m.pushMetrics(y,t)}),a},"metricsProcessor");vo.metricsProcessor=Nw});var xh=g(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.SystemRouteName=void 0;var Nh;(function(e){e.Build="build-data",e.CorsPreflight="cors-preflight",e.DeveloperPortal="developer-portal",e.DeveloperPortalLegacy="developer-portal-legacy",e.EmptyGatewayCatchall="empty-gateway-catchall",e.Ping="ping",e.UnmatchedPath="unmatched-path"})(Nh||(To.SystemRouteName=Nh={}))});var Lh=g(Ch=>{"use strict";Object.defineProperty(Ch,"__esModule",{value:!0})});var Pr=g(Qt=>{"use strict";var xw=Qt&&Qt.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),Dh=Qt&&Qt.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&xw(t,e,r)};Object.defineProperty(Qt,"__esModule",{value:!0});Dh(xh(),Qt);Dh(Lh(),Qt)});var Uh=g(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.registerBuildRoute=void 0;var Cw=Ct(),Lw=Wt(),Dw=Rr(),Uw=Pr(),Mw=mt(),kw=Ke(),Hw=ee(),Fw=o((e,t)=>{let r=o(async(s,a)=>{let u=new URL(s.url).hostname.toLowerCase();if(!u.endsWith(".zuplo.app")&&!u.endsWith(".zuplo.dev")&&!u.endsWith(".fly.dev")&&!u.endsWith("zuplotest.com")&&u!=="localhost")return Cw.HttpProblems.notFound(s,a);let l=Hw.Environment.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&kw.SystemLogMap.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),n=new Lw.Pipeline([Dw.metricsProcessor],r,t),i=new Mw.SystemRouteConfiguration({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:Uw.SystemRouteName.Build});e.addRoute(i,n.execute)},"registerBuildRoute");So.registerBuildRoute=Fw});var Iu=g(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.HTTP_STATUS_TITLES=Jr.HttpStatusCode=void 0;var Mh;(function(e){e[e.CONTINUE=100]="CONTINUE",e[e.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",e[e.PROCESSING=102]="PROCESSING",e[e.EARLY_HINTS=103]="EARLY_HINTS",e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.ACCEPTED=202]="ACCEPTED",e[e.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.RESET_CONTENT=205]="RESET_CONTENT",e[e.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",e[e.MULTI_STATUS=207]="MULTI_STATUS",e[e.ALREADY_REPORTED=208]="ALREADY_REPORTED",e[e.IM_USED=226]="IM_USED",e[e.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.FOUND=302]="FOUND",e[e.SEE_OTHER=303]="SEE_OTHER",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.USE_PROXY=305]="USE_PROXY",e[e.SWITCH_PROXY=306]="SWITCH_PROXY",e[e.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",e[e.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.UNAUTHORIZED=401]="UNAUTHORIZED",e[e.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",e[e.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",e[e.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",e[e.CONFLICT=409]="CONFLICT",e[e.GONE=410]="GONE",e[e.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",e[e.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",e[e.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",e[e.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",e[e.URI_TOO_LONG=414]="URI_TOO_LONG",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",e[e.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",e[e.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",e[e.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",e[e.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",e[e.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",e[e.LOCKED=423]="LOCKED",e[e.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",e[e.TOO_EARLY=425]="TOO_EARLY",e[e.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",e[e.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",e[e.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e[e.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",e[e.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",e[e.LOOP_DETECTED=508]="LOOP_DETECTED",e[e.NOT_EXTENDED=510]="NOT_EXTENDED",e[e.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(Mh||(Jr.HttpStatusCode=Mh={}));Jr.HTTP_STATUS_TITLES={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 Ru=g(Au=>{"use strict";Object.defineProperty(Au,"__esModule",{value:!0});var qw={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"};Au.default=qw});var le=g(zr=>{"use strict";var $w=zr&&zr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(zr,"__esModule",{value:!0});zr.HttpProblems=void 0;var jw=Zn(),N=Iu(),Vw=$w(Ru()),Gw=ee(),Pu=lo();function Bw(e){return`${new URL(e.url).pathname}`}o(Bw,"instance");function Kw(e,t){let r={timestamp:new Date().toISOString(),requestId:t.requestId,buildId:Gw.Environment.instance.build.BUILD_ID},n=e.headers.get(jw.RAY_ID_HEADER);return n&&(r.rayId=n),r}o(Kw,"trace");var Jw=o((e,t,r,n,i)=>({problem:{type:e.type,title:e.title,status:e.status,detail:e.detail,instance:Bw(t),trace:Kw(t,r),...n},additionalHeaders:i,statusText:Vw.default[e.status]}),"merge"),Ou=class{static{o(this,"HttpProblemsBase")}static format=(t,r,n)=>"problem"in t?Pu.ProblemResponseFormatter.format(t,r,n):Pu.ProblemResponseFormatter.format({problem:t},r,n);static getProblemFromStatus(t,r){return{type:`https://httpproblems.com/http-status/${t}`,status:t,title:N.HTTP_STATUS_TITLES[t],...r}}},Nu=class extends Ou{static{o(this,"HttpProblems")}static#e(t,r,n,i,s){let a=Jw(this.getProblemFromStatus(t),r,n,i,s);return Pu.ProblemResponseFormatter.format(a,r,n)}static continue=(t,r,n,i)=>this.#e(N.HttpStatusCode.OK,t,r,n,i);static switchingProtocols=(t,r,n,i)=>this.#e(N.HttpStatusCode.SWITCHING_PROTOCOLS,t,r,n,i);static processing=(t,r,n,i)=>this.#e(N.HttpStatusCode.PROCESSING,t,r,n,i);static earlyHints=(t,r,n,i)=>this.#e(N.HttpStatusCode.EARLY_HINTS,t,r,n,i);static ok=(t,r,n,i)=>this.#e(N.HttpStatusCode.OK,t,r,n,i);static created=(t,r,n,i)=>this.#e(N.HttpStatusCode.CREATED,t,r,n,i);static accepted=(t,r,n,i)=>this.#e(N.HttpStatusCode.ACCEPTED,t,r,n,i);static nonAuthoritativeInformation=(t,r,n,i)=>this.#e(N.HttpStatusCode.NON_AUTHORITATIVE_INFORMATION,t,r,n,i);static noContent=(t,r,n,i)=>this.#e(N.HttpStatusCode.NO_CONTENT,t,r,n,i);static resetContent=(t,r,n,i)=>this.#e(N.HttpStatusCode.RESET_CONTENT,t,r,n,i);static partialContent=(t,r,n,i)=>this.#e(N.HttpStatusCode.PARTIAL_CONTENT,t,r,n,i);static multiStatus=(t,r,n,i)=>this.#e(N.HttpStatusCode.MULTI_STATUS,t,r,n,i);static alreadyReported=(t,r,n,i)=>this.#e(N.HttpStatusCode.ALREADY_REPORTED,t,r,n,i);static imUsed=(t,r,n,i)=>this.#e(N.HttpStatusCode.IM_USED,t,r,n,i);static multipleChoices=(t,r,n,i)=>this.#e(N.HttpStatusCode.MULTIPLE_CHOICES,t,r,n,i);static movedPermanently=(t,r,n,i)=>this.#e(N.HttpStatusCode.MOVED_PERMANENTLY,t,r,n,i);static found=(t,r,n,i)=>this.#e(N.HttpStatusCode.FOUND,t,r,n,i);static seeOther=(t,r,n,i)=>this.#e(N.HttpStatusCode.SEE_OTHER,t,r,n,i);static notModified=(t,r,n,i)=>this.#e(N.HttpStatusCode.NOT_MODIFIED,t,r,n,i);static useProxy=(t,r,n,i)=>this.#e(N.HttpStatusCode.USE_PROXY,t,r,n,i);static switchProxy=(t,r,n,i)=>this.#e(N.HttpStatusCode.SWITCH_PROXY,t,r,n,i);static temporaryRedirect=(t,r,n,i)=>this.#e(N.HttpStatusCode.TEMPORARY_REDIRECT,t,r,n,i);static permanentRedirect=(t,r,n,i)=>this.#e(N.HttpStatusCode.PERMANENT_REDIRECT,t,r,n,i);static badRequest=(t,r,n,i)=>this.#e(N.HttpStatusCode.BAD_REQUEST,t,r,n,i);static unauthorized=(t,r,n,i)=>this.#e(N.HttpStatusCode.UNAUTHORIZED,t,r,n,i);static paymentRequired=(t,r,n,i)=>this.#e(N.HttpStatusCode.PAYMENT_REQUIRED,t,r,n,i);static forbidden=(t,r,n,i)=>this.#e(N.HttpStatusCode.FORBIDDEN,t,r,n,i);static notFound=(t,r,n,i)=>this.#e(N.HttpStatusCode.NOT_FOUND,t,r,n,i);static methodNotAllowed=(t,r,n,i)=>this.#e(N.HttpStatusCode.METHOD_NOT_ALLOWED,t,r,n,i);static notAcceptable=(t,r,n,i)=>this.#e(N.HttpStatusCode.NOT_ACCEPTABLE,t,r,n,i);static proxyAuthenticationRequired=(t,r,n,i)=>this.#e(N.HttpStatusCode.PROXY_AUTHENTICATION_REQUIRED,t,r,n,i);static requestTimeout=(t,r,n,i)=>this.#e(N.HttpStatusCode.REQUEST_TIMEOUT,t,r,n,i);static conflict=(t,r,n,i)=>this.#e(N.HttpStatusCode.CONFLICT,t,r,n,i);static gone=(t,r,n,i)=>this.#e(N.HttpStatusCode.GONE,t,r,n,i);static lengthRequired=(t,r,n,i)=>this.#e(N.HttpStatusCode.LENGTH_REQUIRED,t,r,n,i);static preconditionFailed=(t,r,n,i)=>this.#e(N.HttpStatusCode.PRECONDITION_FAILED,t,r,n,i);static contentTooLarge=(t,r,n,i)=>this.#e(N.HttpStatusCode.CONTENT_TOO_LARGE,t,r,n,i);static uriTooLong=(t,r,n,i)=>this.#e(N.HttpStatusCode.URI_TOO_LONG,t,r,n,i);static unsupportedMediaType=(t,r,n,i)=>this.#e(N.HttpStatusCode.UNSUPPORTED_MEDIA_TYPE,t,r,n,i);static rangeNotSatisfiable=(t,r,n,i)=>this.#e(N.HttpStatusCode.RANGE_NOT_SATISFIABLE,t,r,n,i);static expectationFailed=(t,r,n,i)=>this.#e(N.HttpStatusCode.EXPECTATION_FAILED,t,r,n,i);static imATeapot=(t,r,n,i)=>this.#e(N.HttpStatusCode.I_AM_A_TEAPOT,t,r,n,i);static misdirectedRequest=(t,r,n,i)=>this.#e(N.HttpStatusCode.MISDIRECTED_REQUEST,t,r,n,i);static unprocessableContent=(t,r,n,i)=>this.#e(N.HttpStatusCode.UNPROCESSABLE_CONTENT,t,r,n,i);static locked=(t,r,n,i)=>this.#e(N.HttpStatusCode.LOCKED,t,r,n,i);static failedDependency=(t,r,n,i)=>this.#e(N.HttpStatusCode.FAILED_DEPENDENCY,t,r,n,i);static tooEarly=(t,r,n,i)=>this.#e(N.HttpStatusCode.TOO_EARLY,t,r,n,i);static upgradeRequired=(t,r,n,i)=>this.#e(N.HttpStatusCode.UPGRADE_REQUIRED,t,r,n,i);static preconditionRequired=(t,r,n,i)=>this.#e(N.HttpStatusCode.PRECONDITION_REQUIRED,t,r,n,i);static tooManyRequests=(t,r,n,i)=>this.#e(N.HttpStatusCode.TOO_MANY_REQUESTS,t,r,n,i);static requestHeaderFieldsTooLarge=(t,r,n,i)=>this.#e(N.HttpStatusCode.REQUEST_HEADER_FIELDS_TOO_LARGE,t,r,n,i);static unavailableForLegalReasons=(t,r,n,i)=>this.#e(N.HttpStatusCode.UNAVAILABLE_FOR_LEGAL_REASONS,t,r,n,i);static internalServerError=(t,r,n,i)=>this.#e(N.HttpStatusCode.INTERNAL_SERVER_ERROR,t,r,n,i);static notImplemented=(t,r,n,i)=>this.#e(N.HttpStatusCode.NOT_IMPLEMENTED,t,r,n,i);static badGateway=(t,r,n,i)=>this.#e(N.HttpStatusCode.BAD_GATEWAY,t,r,n,i);static serviceUnavailable=(t,r,n,i)=>this.#e(N.HttpStatusCode.SERVICE_UNAVAILABLE,t,r,n,i);static gatewayTimeout=(t,r,n,i)=>this.#e(N.HttpStatusCode.GATEWAY_TIMEOUT,t,r,n,i);static httpVersionNotSupported=(t,r,n,i)=>this.#e(N.HttpStatusCode.HTTP_VERSION_NOT_SUPPORTED,t,r,n,i);static variantAlsoNegotiates=(t,r,n,i)=>this.#e(N.HttpStatusCode.VARIANT_ALSO_NEGOTIATES,t,r,n,i);static insufficientStorage=(t,r,n,i)=>this.#e(N.HttpStatusCode.INSUFFICIENT_STORAGE,t,r,n,i);static loopDetected=(t,r,n,i)=>this.#e(N.HttpStatusCode.LOOP_DETECTED,t,r,n,i);static notExtended=(t,r,n,i)=>this.#e(N.HttpStatusCode.NOT_EXTENDED,t,r,n,i);static networkAuthenticationRequired=(t,r,n,i)=>this.#e(N.HttpStatusCode.NETWORK_AUTHENTICATION_REQUIRED,t,r,n,i)};zr.HttpProblems=Nu});var Yt=g(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.isErrorLike=M.withUndefinedAsNull=M.withNullAsUndefined=M.validateConstraint=M.validateConstraints=M.areFunctions=M.isFunction=M.isEmptyObject=M.assertAllDefined=M.assertIsDefined=M.assertType=M.isUndefinedOrNull=M.isDefined=M.isUndefined=M.isBoolean=M.isIterable=M.isNumber=M.isTypedArray=M.isArray=M.isObject=M.getOwnEnumerableKeys=M.isRegexp=M.isStringArray=M.isNonEmptyString=M.isString=M.toString=void 0;var{toString:zw}=Object.prototype,{propertyIsEnumerable:Ww}=Object.prototype;function kh(e){return zw.call(e)}o(kh,"toString");M.toString=kh;function Io(e){return typeof e=="string"}o(Io,"isString");M.isString=Io;function Qw(e){return Io(e)&&e!==""}o(Qw,"isNonEmptyString");M.isNonEmptyString=Qw;function Yw(e){return Array.isArray(e)&&e.every(t=>Io(t))}o(Yw,"isStringArray");M.isStringArray=Yw;function Zw(e){return kh(e)==="[object RegExp]"}o(Zw,"isRegexp");M.isRegexp=Zw;function Xw(e){return[...Object.keys(e),...Object.getOwnPropertySymbols(e).filter(t=>Ww.call(e,t))]}o(Xw,"getOwnEnumerableKeys");M.getOwnEnumerableKeys=Xw;function xu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}o(xu,"isObject");M.isObject=xu;function ev(e){return xu(e)&&Array.isArray(e)}o(ev,"isArray");M.isArray=ev;function tv(e){let t=Object.getPrototypeOf(Uint8Array);return typeof e=="object"&&e instanceof t}o(tv,"isTypedArray");M.isTypedArray=tv;function rv(e){return typeof e=="number"&&!isNaN(e)}o(rv,"isNumber");M.isNumber=rv;function nv(e){return!!e&&typeof e[Symbol.iterator]=="function"}o(nv,"isIterable");M.isIterable=nv;function iv(e){return e===!0||e===!1}o(iv,"isBoolean");M.isBoolean=iv;function Hh(e){return typeof e>"u"}o(Hh,"isUndefined");M.isUndefined=Hh;function ov(e){return!ei(e)}o(ov,"isDefined");M.isDefined=ov;function ei(e){return Hh(e)||e===null}o(ei,"isUndefinedOrNull");M.isUndefinedOrNull=ei;function sv(e,t){if(!e)throw new Error(t?`Unexpected type, expected '${t}'`:"Unexpected type")}o(sv,"assertType");M.assertType=sv;function av(e){if(ei(e))throw new Error("Assertion Failed: argument is undefined or null");return e}o(av,"assertIsDefined");M.assertIsDefined=av;function cv(...e){let t=[];for(let r=0;r<e.length;r++){let n=e[r];if(ei(n))throw new Error(`Assertion Failed: argument at index ${r} is undefined or null`);t.push(n)}return t}o(cv,"assertAllDefined");M.assertAllDefined=cv;var uv=Object.prototype.hasOwnProperty;function lv(e){if(!xu(e))return!1;for(let t in e)if(uv.call(e,t))return!1;return!0}o(lv,"isEmptyObject");M.isEmptyObject=lv;function Cu(e){return typeof e=="function"}o(Cu,"isFunction");M.isFunction=Cu;function dv(...e){return e.length>0&&e.every(Cu)}o(dv,"areFunctions");M.areFunctions=dv;function pv(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)Fh(e[n],t[n])}o(pv,"validateConstraints");M.validateConstraints=pv;function Fh(e,t){if(Io(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(Cu(t)){try{if(e instanceof t)return}catch{}if(!ei(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}o(Fh,"validateConstraint");M.validateConstraint=Fh;function hv(e){return e===null?void 0:e}o(hv,"withNullAsUndefined");M.withNullAsUndefined=hv;function fv(e){return typeof e>"u"?null:e}o(fv,"withUndefinedAsNull");M.withUndefinedAsNull=fv;function mv(e){return!!e&&typeof e=="object"&&"name"in e&&"message"in e&&"stack"in e}o(mv,"isErrorLike");M.isErrorLike=mv});var ti=g(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.parseValueToBoolean=yt.parseValueToStringArray=yt.getValueFromRequestUser=yt.statusCodesStringToNumberArray=void 0;var Wr=D(),Lu=Yt(),qh=new Map;function yv(e){if(typeof e!="string")throw new Error("Input must be a string");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(e))throw new Error("Malformed input string");let t=qh.get(e);if(t)return t;let r=e.split(","),n=[];for(let i of r){let s=i.split("-");if(s.length===2){let a=parseInt(s[0],10),c=parseInt(s[1],10);for(let u=a;u<=c;u++)n.push(u)}else n.push(parseInt(i,10))}return qh.set(e,n),n}o(yv,"statusCodesStringToNumberArray");yt.statusCodesStringToNumberArray=yv;function gv(e,t,r){if(!t.startsWith("."))throw new Wr.ConfigurationError(`Invalid ${r} - must start with '.' - '${t}' does not`);let n=t.split(".").splice(1),i=e;return n.forEach(s=>{if(i===void 0)throw new Wr.RuntimeError(`Error applying ${r} '${t}', reading '${s}'`);i=i[s]}),`${i}`}o(gv,"getValueFromRequestUser");yt.getValueFromRequestUser=gv;function bv(e){if(Array.isArray(e)){if(e.includes(r=>typeof r!="string"))throw new Wr.ConfigurationError("Received an array that contains non-string values.");return e}if((0,Lu.isString)(e))return e.includes(",")?e.split(",").map(r=>r.trim()).filter(r=>r!==","&&r!==""):[e];throw new Wr.ConfigurationError(`Expected type of string, received type '${typeof e}'`)}o(bv,"parseValueToStringArray");yt.parseValueToStringArray=bv;function _v(e){if((0,Lu.isBoolean)(e))return e;if((0,Lu.isString)(e)){if(e.toLowerCase()==="true")return!0;if(e.toLowerCase()==="false")return!1;throw new Wr.ConfigurationError(`Attempted to parse string to boolean, but received ${e} which cannot be parsed.`)}throw new Wr.ConfigurationError(`Expected type of boolean, received type '${typeof e}'`)}o(_v,"parseValueToBoolean");yt.parseValueToBoolean=_v});var Ro=g(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.generateCorsHeaders=Zt.findMatchingOrigin=Zt.parseCorsPolicies=void 0;var Or=D(),$h=ti(),Ao=Yt();function Ev(e){if(e==null)return[];if(!Array.isArray(e))throw new Or.ConfigurationError(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof e}'`);return e.map(r=>{if(!(0,Ao.isObject)(r))throw new Or.ConfigurationError(`Invalid custom cors policy is set. Expected an object, received '${typeof r}'`);if(!(0,Ao.isNonEmptyString)(r.name))throw new Or.ConfigurationError("Value of 'name' on custom cors policies must be a non-empty string.");if(r.maxAge!==void 0&&!(0,Ao.isNumber)(r.maxAge))throw new Or.ConfigurationError(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof r.maxAge}'`);if(r.allowCredentials!==void 0&&!(0,Ao.isBoolean)(r.allowCredentials))throw new Or.ConfigurationError("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 n=Du(r,"allowedHeaders"),i=Du(r,"allowedMethods"),s=Du(r,"exposeHeaders"),a;try{a=(0,$h.parseValueToStringArray)(r.allowedOrigins)}catch(u){throw new Or.ConfigurationError(`Value of 'allowedOrigins' on custom cors policies is invalid. ${u.message} If using an environment variable, check that it is set correctly.`)}return{name:r.name,allowCredentials:typeof r.allowCredentials=="boolean"?String(r.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:n?n.join(", "):void 0,allowedMethods:i?i.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof r.maxAge=="number"?r.maxAge.toString():void 0}})}o(Ev,"parseCorsPolicies");Zt.parseCorsPolicies=Ev;function Du(e,t){let r;if(e[t]!==void 0)try{r=(0,$h.parseValueToStringArray)(e[t])}catch(n){throw new Or.ConfigurationError(`Value of '${t}' on custom cors policies is invalid. ${n.message} If using an environment variable, check that it is set correctly.`)}return r}o(Du,"parseOptionalProperty");var wv=o((e,t)=>{if(t===null)return;if(e.find(a=>a==="*"))return t;let n=e.map(a=>a.trim().toLowerCase()),i=t.toLowerCase();return n.find(a=>a===i)},"findMatchingOrigin");Zt.findMatchingOrigin=wv;var vv=o((e,t)=>{let r={"access-control-allow-origin":t};e.allowedHeaders&&(r["access-control-allow-headers"]=e.allowedHeaders),e.allowedMethods&&(r["access-control-allow-methods"]=e.allowedMethods),e.exposeHeaders&&(r["access-control-expose-headers"]=e.exposeHeaders);let n=e.allowCredentials;n&&(r["access-control-allow-credentials"]=n);let i=e.maxAge?.toString()??void 0;return i&&(r["access-control-max-age"]=i),r},"generateCorsHeaders");Zt.generateCorsHeaders=vv});var Vh=g(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.registerCorsRoute=void 0;var Tv=D(),Sv=Wt(),Uu=le(),Iv=Rr(),Av=Pr(),Rv=mt(),jh=Ro(),Pv=o((e,t)=>{let r=t.routeData.corsPolicies,n=o(async(a,c)=>{let u=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return Uu.HttpProblems.badRequest(a,c,{detail:"Expect headers origin and access-control-request-method"});let y=e.lookup(l,u);if(!y)return Uu.HttpProblems.notFound(a,c);let h=y.routeConfiguration,m=Ov(l,d,p,h,r);return m.isValid?new Response(void 0,{status:200,statusText:"OK",headers:m.headers}):(m.error&&c.log.warn(m.error),Uu.HttpProblems.notFound(a,c))},"optionsHandler"),i=new Sv.Pipeline([Iv.metricsProcessor],n,t),s=new Rv.SystemRouteConfiguration({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:Av.SystemRouteName.CorsPreflight});e.addRoute(s,i.execute)},"registerCorsRoute");Po.registerCorsRoute=Pv;var Ov=o((e,t,r,n,i)=>{let s={isValid:!1,headers:{}};if(n.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":r,"access-control-allow-methods":e,"access-control-allow-headers":t??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(n.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${n.pathPattern}'`};let a=i?.find(l=>l.name===n.corsPolicy);if(!a)throw new Tv.ConfigurationError(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let c=(0,jh.findMatchingOrigin)(a.allowedOrigins,r);return c?{isValid:!0,headers:(0,jh.generateCorsHeaders)(a,c)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${r}'`}},"validateAndBuildResponseHeaders")});var Gh=g(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.registerNoRoutes=void 0;var Nv=Wt(),xv=Rr(),Cv=Pr(),Lv=mt(),Dv=o((e,t)=>{let r=o(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),n=new Nv.Pipeline([xv.metricsProcessor],r,t),i=new Lv.SystemRouteConfiguration({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:Cv.SystemRouteName.EmptyGatewayCatchall});e.addRoute(i,n.execute)},"registerNoRoutes");Oo.registerNoRoutes=Dv});var Bh=g(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.registerNotMatchedHandler=Nr.notFoundRouteConfiguration=void 0;var Uv=Ir(),Mv=xt(),kv=Wt(),Hv=le(),Fv=Rr(),qv=Pr(),$v=mt();Nr.notFoundRouteConfiguration=new $v.SystemRouteConfiguration({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:qv.SystemRouteName.UnmatchedPath});var jv=o((e,t)=>{let r=o(async(i,s)=>{let a=Mv.runtimeExtensions.value?.notFoundHandler;if(a){let c=Uv.ZuploContextExtensions.getContextExtensions(s);return a(i,s,{routesMatchedByPathOnly:c.pathOnlyMatches??[]})}return Hv.HttpProblems.notFound(i,s)},"notFoundHandler"),n=new kv.Pipeline([Fv.metricsProcessor],r,t);e.addRoute(Nr.notFoundRouteConfiguration,n.execute)},"registerNotMatchedHandler");Nr.registerNotMatchedHandler=jv});var Mu=g(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.corsProcessor=void 0;var zh=D(),Kh=Ro(),Vv=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Jh=o(e=>{Vv.forEach(t=>e.delete(t))},"stripCorsHeaders"),Gv=o(async(e,t,r,n)=>{let i=t.route;if(!i.corsPolicy||i.corsPolicy==="none"){let d=await n(e),p=new Headers(d.headers);return Jh(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await n(e);if(!(s instanceof Response))throw new zh.SystemError(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Bv(i,r.routeData.corsPolicies),c=Kv(e,a),u=new Headers(s.headers);return Jh(u),Object.entries(c).forEach(([d,p])=>{u.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:u,webSocket:s.webSocket})},"corsProcessor");No.corsProcessor=Gv;var Bv=o((e,t)=>{if(e.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:e.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let r=t?.find(n=>n.name===e.corsPolicy);if(r===void 0)throw new zh.ConfigurationError(`Invalid Configuration - no corsPolicy '${e.corsPolicy}' found in *.oas.json`);return r},"getCorsPolicy"),Kv=o((e,t)=>{let r=(0,Kh.findMatchingOrigin)(t.allowedOrigins,e.headers.get("origin"));return r?(0,Kh.generateCorsHeaders)(t,r):{}},"getCorsHeaders")});var Wh=g(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.registerPingRoute=void 0;var Jv=Wt(),zv=Mu(),Wv=Pr(),Qv=mt(),Yv=o((e,t)=>{let r=o(async()=>new Response(null,{status:200}),"pingRouteHandler"),n=new Jv.Pipeline([zv.corsProcessor],r,t),i=new Qv.SystemRouteConfiguration({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:Wv.SystemRouteName.Ping});e.addRoute(i,n.execute)},"registerPingRoute");xo.registerPingRoute=Yv});var Yh=g(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.deepFreeze=void 0;function Qh(e){for(let t in e){let r=e[t];r&&typeof r=="object"&&Qh(r)}return Object.freeze(e)}o(Qh,"deepFreeze");Co.deepFreeze=Qh});var Je=g(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.ZuploRequest=void 0;var Zh=Yh(),ku=class e extends Request{static{o(this,"ZuploRequest")}#e=void 0;#t;constructor(t,r){super(t,r);let n=r?.params;n?this.#t=n:t instanceof e?this.#t=t.#t:this.#t={};let i=r?.user;i?this.user=i:t instanceof e&&(this.user=t.user)}get query(){if(this.#e===void 0){let t={},r=new URL(this.url).searchParams;for(let[n,i]of r.entries())t[n]=i;this.#e=t}return(0,Zh.deepFreeze)(this.#e)}get params(){return(0,Zh.deepFreeze)(this.#t)}user};Lo.ZuploRequest=ku});var ri=g(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.policyProcessor=Lt.toStackedInboundHandler=Lt.getInboundPolicyHandlerAndOptions=void 0;var Zv=Ir(),Qr=D(),Xh=Je(),Xv=ee();function ef(e,t){let r,n;return Array.isArray(e)?r=e:(r=e.policies?.inbound??[],n=e.path),r.map(s=>{let a=t?.find(u=>u.name===s);if(!a)throw new Qr.ConfigurationError(`Invalid state - no Policy with the name '${s}' ${n&&`on route '${n}'`} was found in the policies configuration (check case).`);let c;if(typeof a.handler?.module=="object"&&(c=a.handler?.module[a.handler.export]),typeof c!="function")throw new Qr.ConfigurationError(`Invalid state - invalid handler on policy '${s}' ${n&&`on route '${n}'`}. Expected a function, received '${typeof c}'`);return{exportName:a.handler.export,handler:c,options:a.handler.options,policyName:a.name}})}o(ef,"getInboundPolicyHandlerAndOptions");Lt.getInboundPolicyHandlerAndOptions=ef;function eT(e,t){return(e.policies?.outbound??[]).map(i=>{let s=t?.find(c=>c.name===i);if(!s)throw new Qr.ConfigurationError(`Invalid state - no Policy with the name '${i}' on route '${e.path}' was found in the policies configuration (check case).`);let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new Qr.ConfigurationError(`Invalid state - invalid handler on policy '${i}' on route '${e.path}'`);return{exportName:s.handler.export,handler:a,options:s.handler.options,policyName:s.name}})}o(eT,"getOutboundPolicyHandlerAndOptions");var tT=o(e=>async(t,r)=>{let n=Zv.ZuploContextExtensions.getContextExtensions(r),i=[...e],s=t;for(;i.length>0;){let a=i.shift();if(!a)return s;let c=await a.handler(s,r,a.options,a.policyName);if(c instanceof Xh.ZuploRequest)s=c;else if(c instanceof Request)s=new Xh.ZuploRequest(c);else{if(c instanceof Response)return c;throw new Qr.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an inbound policy must be a Response or Request.`)}n.latestRequest=s}return s},"toStackedInboundHandler");Lt.toStackedInboundHandler=tT;var rT=o(e=>async(t,r,n)=>{let i=[...e],s=t;for(;i.length>0;){let a=i.shift();if(!a)return s;let c=await a.handler(s,r,n,a.options,a.policyName);if(!(c instanceof Response))throw new Qr.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an outbound policy must be a Response.`);s=c}return s},"toStackedOutboundHandler"),nT=o(async(e,t,r,n)=>{let i=ef(t.route,r.routeData.policies),s=eT(t.route,r.routeData.policies),a=(0,Lt.toStackedInboundHandler)(i);try{let c=await a(e,t);if(c instanceof Response)return c;let u=await n(c),l=rT(s),d;return Xv.Environment.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(u,e,t):d=u.ok?l(u,e,t):u,d}catch(c){return t.log.error(c),r.errorHandler(e,t,c)}},"policyProcessor");Lt.policyProcessor=nT});var tf=g(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.serialize=Yr.parse=void 0;var iT=Object.prototype.toString,Do=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function oT(e,t){if(typeof e!="string")throw new TypeError("argument str must be a string");let r={},i=(t||{}).decode||aT,s=0;for(;s<e.length;){let a=e.indexOf("=",s);if(a===-1)break;let c=e.indexOf(";",s);if(c===-1)c=e.length;else if(c<a){s=e.lastIndexOf(";",a-1)+1;continue}let u=e.slice(s,a).trim();if(r[u]===void 0){let l=e.slice(a+1,c).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),r[u]=lT(l,i)}s=c+1}return r}o(oT,"parse");Yr.parse=oT;function sT(e,t,r){let n=r||{},i=n.encode||cT;if(typeof i!="function")throw new TypeError("option encode is invalid");if(!Do.test(e))throw new TypeError("argument name is invalid");let s=i(t);if(s&&!Do.test(s))throw new TypeError("argument val is invalid");let a=e+"="+s;if(n.maxAge!=null){let c=n.maxAge-0;if(isNaN(c)||!isFinite(c))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(c)}if(n.domain){if(!Do.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!Do.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){let c=n.expires;if(!uT(c)||isNaN(c.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+c.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return a}o(sT,"serialize");Yr.serialize=sT;function aT(e){return e.indexOf("%")!==-1?decodeURIComponent(e):e}o(aT,"decode");function cT(e){return encodeURIComponent(e)}o(cT,"encode");function uT(e){return iT.call(e)==="[object Date]"||e instanceof Date}o(uT,"isDate");function lT(e,t){try{return t(e)}catch{return e}}o(lT,"tryDecode")});var rf=g(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.devPortalBaseURL=void 0;var dT=tf();function pT(e,t){try{let r=/v\d+(-\d+)?/g,i=(0,dT.parse)(t.get("Cookie")||"")["zp-dev-portal"];return i!==null&&i&&r.test(i)?`https://dev-portal-${i}.zuplo.com`:e}catch{}return e}o(pT,"devPortalBaseURL");Uo.devPortalBaseURL=pT});var cf=g(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.registerDevPortalLegacyRedirectRoute=Zr.registerDevPortalV3Route=void 0;var Hu=Ct(),of=Wt(),sf=Rr(),hT=ri(),af=mt(),fT=rf(),Xt=ee(),nf="/__zuplo/dev-portal",mT="dev-portal-id",yT="dev-portal-host",gT="zp-account",bT="zp-project",_T="dev-portal-build",ET=`
35
+ `)+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}o(ow,"reduceToSingleString")});var wh=g(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.format=void 0;var sw=fh(),aw=Eh(),cw=o((e,...t)=>(0,sw.format)(aw.inspect,e,t),"format");so.format=cw});var Sr=g(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.debug=Jt.withoutEnv=Jt.Debugger=void 0;var uw=hh(),lw=wh(),ao=class{static{o(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,r){this.manager=t,this.ns=r,this.color=(0,uw.generateColor)(r),this.last=0,this.enabled=t.enabled.some(n=>n.test(r))}log(...t){if(!this.enabled)return;let r,n=t[0];typeof n=="function"?r=n():r=String(n);let i=Date.now()-(this.last||Date.now());r=(0,lw.format)(r,...t);let s=`${this.color(this.ns)} ${r} ${this.color(`+${i}ms`)}`;console.log(s),this.last=Date.now()}};Jt.Debugger=ao;var co=class{static{o(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function vh(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}o(vh,"extract");var Xn;function dw(e){e||(e=[]),typeof e=="string"&&(e=vh(e)),Xn=new co(e)}o(dw,"withoutEnv");Jt.withoutEnv=dw;function pw(e){let t=globalThis.DEBUG;Xn||(Xn=new co(vh(t)));let r=new ao(Xn,e);return Xn.debuggers.set(e,r),Object.assign(r.log.bind(r),{self:r})}o(pw,"debug");Jt.debug=pw});var lo=g(Kr=>{"use strict";Object.defineProperty(Kr,"__esModule",{value:!0});Kr.ProblemResponseFormatter=Kr.InternalProblemResponseFormatter=void 0;var hw=D(),uo=class e{static{o(this,"InternalProblemResponseFormatter")}static problemResponseFormat=async t=>{let r=t.problem,n=JSON.stringify(r,null,2);return new Response(n,{status:t.problem.status,statusText:t.statusText,headers:{...t.additionalHeaders,"content-type":"application/problem+json"}})};static setProblemResponseFormat(t){t&&(e.problemResponseFormat=(r,n,i)=>{try{return t(r,n,i)}catch(s){throw new hw.RuntimeError("Error in custom 'problemResponseFormat'",{cause:s})}})}};Kr.InternalProblemResponseFormatter=uo;var mu=class{static{o(this,"ProblemResponseFormatter")}static async format(t,r,n){return await uo.problemResponseFormat(t,r,n)}};Kr.ProblemResponseFormatter=mu});var xt=g(be=>{"use strict";Object.defineProperty(be,"__esModule",{value:!0});be.initializeRuntime=be.invokeOnResponseSendingFinalExtensions=be.invokeOnResponseSendingExtensions=be.invokeOnRequestExtensions=be.plugins=be.runtimeExtensions=be.InitializableRuntimePlugin=be.RuntimePlugin=void 0;var fw=lo(),ho=class{static{o(this,"RuntimePlugin")}};be.RuntimePlugin=ho;var fo=class extends ho{static{o(this,"InitializableRuntimePlugin")}};be.InitializableRuntimePlugin=fo;be.runtimeExtensions={};var yu=[];be.plugins=yu;var Th=[],Sh=[],Ih=[],po={addPlugin(e){yu.push(e)},addRequestHook(e){Th.push(e)},addResponseSendingHook(e){Sh.push(e)},addResponseSendingFinalHook(e){Ih.push(e)}},mw=o(async(e,t)=>{let r=e;for(let n of Th)if(r=await n(r,t),r instanceof Response)return r;return r},"invokeOnRequestExtensions");be.invokeOnRequestExtensions=mw;var yw=o(async(e,t,r)=>{let n=e;for(let i of Sh)n=await i(e,t,r);return n},"invokeOnResponseSendingExtensions");be.invokeOnResponseSendingExtensions=yw;var gw=o(async(e,t,r)=>{for(let n of Ih)await n(e,t,r)},"invokeOnResponseSendingFinalExtensions");be.invokeOnResponseSendingFinalExtensions=gw;async function bw(e=()=>Promise.resolve()){await e(po),be.runtimeExtensions.value=po;let t=yu.filter(r=>r instanceof fo);for(let r of t)await r.initialize(po);fw.InternalProblemResponseFormatter.setProblemResponseFormat(po.problemResponseFormat)}o(bw,"initializeRuntime");be.initializeRuntime=bw});var gu=g(zt=>{"use strict";Object.defineProperty(zt,"__esModule",{value:!0});zt.serialize=zt.ContentTypes=void 0;zt.ContentTypes={Json:"application/json",Form:"application/x-www-form-urlencoded"};function _w(e,t){if(e!==null)return t&&typeof e=="string"?e:typeof e=="object"&&t?.startsWith(zt.ContentTypes.Form)?new URLSearchParams(e).toString():typeof e=="object"&&t?.startsWith(zt.ContentTypes.Json)||!t?JSON.stringify(e):e}o(_w,"serialize");zt.serialize=_w});var Wt=g(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.Pipeline=void 0;var bu=Ir(),Ah=xt(),Ew=gu(),_u=class{static{o(this,"Pipeline")}constructor(t){this.execute=this.#t(t)}execute;#e=(t,r)=>async(n,i)=>{try{return await t(n,i)}catch(s){return i.log.error("Error executing request handler.",s),r.errorHandler(n,i,s)}};#t=({processors:t,gateway:r,handler:n})=>async(i,s)=>{let a=[...t],c=o(async m=>{let v=a.pop();return v?v(i,s,r,c):await this.#e(async S=>{let O=await n(S,s);return ww(O)},r)(m,s)},"nextPipe"),l=await c(i),d=new bu.ResponseSendingEvent(i,l);s.dispatchEvent(d);let p=bu.ZuploContextExtensions.getContextExtensions(s),y=p.latestRequest,h;try{h=await d.mutableResponse}catch(m){return s.log.error(m),r.errorHandler(i,s,m)}try{h=await p.onResponseSending(h,y,s)}catch(m){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${m.message}'`,m),r.errorHandler(i,s,m)}try{h=await(0,Ah.invokeOnResponseSendingExtensions)(h,y,s)}catch(m){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${m.message}'`,m),r.errorHandler(i,s,m)}s.dispatchEvent(new bu.ResponseSentEvent(i,h));try{await p.onResponseSendingFinal(l,y,s)}catch(m){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${m.message}'`,m),m}try{await(0,Ah.invokeOnResponseSendingFinalExtensions)(l,y,s)}catch(m){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${m.message}'`,m),m}return h}};mo.Pipeline=_u;function ww(e){return e instanceof Response?e:typeof e>"u"?new Response:new Response((0,Ew.serialize)(e),{headers:{"content-type":"application/json"}})}o(ww,"resultToResponse")});var go=g(yo=>{"use strict";Object.defineProperty(yo,"__esModule",{value:!0});yo.MetricsPlugin=void 0;var vw=xt(),Eu=class extends vw.RuntimePlugin{static{o(this,"MetricsPlugin")}};yo.MetricsPlugin=Eu});var Ke=g(bo=>{"use strict";Object.defineProperty(bo,"__esModule",{value:!0});bo.SystemLogMap=void 0;var Tw=D(),wu=class e{static{o(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(t){let r=e.#e.get(t);if(!r){let n=`No system logger found for context with requestId '${t.requestId}'`;throw console.error(n),new Tw.SystemError(n)}return r}static addLogger(t,r){e.#e.set(t,r)}};bo.SystemLogMap=wu});var Se=g(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.BatchDispatch=void 0;var vu=class{static{o(this,"BatchDispatch")}constructor(t,r,n,i){this.#t=t,this.#o=r,this.#n=n,this.#r=i}#e=void 0;#t;#r;#n;#i=[];#o;enqueue=t=>{this.#i.push(t),this.#e||(this.#e=new Promise(r=>{setTimeout(()=>{if(this.#i.length>0){let n=[...this.#i];this.#i.length=0,this.#e=void 0,this.#n(n).catch(i=>{this.#r&&this.#r.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,i.message,i.stack)}).finally(()=>{r()})}},this.#o)}))};waitUntilFlushed=async()=>{if(this.#e)return this.#e}};_o.BatchDispatch=vu});var Ph=g(wo=>{"use strict";Object.defineProperty(wo,"__esModule",{value:!0});wo.EllieMetricsTransport=void 0;var Rh=Ke(),Sw=Se(),Eo=ee(),Tu=class{static{o(this,"EllieMetricsTransport")}#e;#t;#r;constructor(t){this.#r=Eo.Environment.instance.loggingId,this.#e=t,this.#t=new Sw.BatchDispatch("ellie-metrics-transport",10,this.dispatchFunction,Rh.SystemLogMap.getLogger(t))}pushMetrics(t,r){this.#r!==void 0&&(this.#t.enqueue(t),r.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=async t=>{if(t.length===0)return;let r,{loggingId:n,remoteLogURL:i,deploymentName:s}=Eo.Environment.instance,a=t.map(c=>{let u=Object.assign({},c);return delete u.requestContentLength,delete u.responseContentLength,u});if(n&&s&&(r=`${i}/v1-alpha/metrics?loggingId=${encodeURI(n)}&deploymentName=${encodeURI(s)}`),r){let c=await fetch(r,{method:"POST",body:JSON.stringify(a),headers:{"content-type":"application/json","zp-dn":Eo.Environment.instance.deploymentName??"unknown","user-agent":Eo.Environment.instance.systemUserAgent}});if(!c.ok){let u=await c.text();Rh.SystemLogMap.getLogger(this.#e).error(`Metrics POST responded ${c.status}: ${c.statusText}`,u)}}}};wo.EllieMetricsTransport=Tu});var mt=g(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.systemNoVersion=Ar.SystemRouteConfiguration=void 0;var Su=class{static{o(this,"SystemRouteConfiguration")}constructor({label:t,path:r,methods:n,systemRouteName:i,corsPolicy:s="none"}){this.label=t,this.path=r,this.methods=n,this.corsPolicy=s,this.version=Ar.systemNoVersion.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=i}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}};Ar.SystemRouteConfiguration=Su;Ar.systemNoVersion={name:"__system-no-version",pathPrefix:""}});var Rr=g(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.metricsProcessor=void 0;var Oh=Zn(),Iw=Ir(),Aw=xt(),Rw=go(),Pw=Ph(),Ow=mt(),Nw=o(async(e,t,r,n)=>{let i=new Date,s=Date.now(),a=await n(e),c=e.headers.get(Oh.RAY_ID_HEADER)??void 0,u=e.headers.get(Oh.TRUE_CLIENT_IP)??void 0,l=t.incomingRequestProperties,d;t.route instanceof Ow.SystemRouteConfiguration&&(d=t.route.systemRouteName);let p=Iw.ZuploContextExtensions.getContextExtensions(t).latestRequest,y={timestamp:i,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:e.headers.get("content-length")?Number(e.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:t.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:t.requestId,method:e.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:c,instanceId:r.instanceId,userSub:p.user?.sub,clientIp:u},h=[];return h.push(new Pw.EllieMetricsTransport(t)),Aw.plugins.forEach(m=>{if(m instanceof Rw.MetricsPlugin){let v=m.getTransport();h.push(v)}}),h.forEach(m=>{m.pushMetrics(y,t)}),a},"metricsProcessor");vo.metricsProcessor=Nw});var xh=g(To=>{"use strict";Object.defineProperty(To,"__esModule",{value:!0});To.SystemRouteName=void 0;var Nh;(function(e){e.Build="build-data",e.CorsPreflight="cors-preflight",e.DeveloperPortal="developer-portal",e.DeveloperPortalLegacy="developer-portal-legacy",e.EmptyGatewayCatchall="empty-gateway-catchall",e.Ping="ping",e.UnmatchedPath="unmatched-path"})(Nh||(To.SystemRouteName=Nh={}))});var Lh=g(Ch=>{"use strict";Object.defineProperty(Ch,"__esModule",{value:!0})});var Pr=g(Qt=>{"use strict";var xw=Qt&&Qt.__createBinding||(Object.create?function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]}),Dh=Qt&&Qt.__exportStar||function(e,t){for(var r in e)r!=="default"&&!Object.prototype.hasOwnProperty.call(t,r)&&xw(t,e,r)};Object.defineProperty(Qt,"__esModule",{value:!0});Dh(xh(),Qt);Dh(Lh(),Qt)});var Uh=g(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.registerBuildRoute=void 0;var Cw=Ct(),Lw=Wt(),Dw=Rr(),Uw=Pr(),Mw=mt(),kw=Ke(),Hw=ee(),Fw=o((e,t)=>{let r=o(async(s,a)=>{let u=new URL(s.url).hostname.toLowerCase();if(!u.endsWith(".zuplo.app")&&!u.endsWith(".zuplo.dev")&&!u.endsWith(".fly.dev")&&!u.endsWith("zuplotest.com")&&u!=="localhost")return Cw.HttpProblems.notFound(s,a);let l=Hw.Environment.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&kw.SystemLogMap.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),n=new Lw.Pipeline({processors:[Dw.metricsProcessor],handler:r,gateway:t}),i=new Mw.SystemRouteConfiguration({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:Uw.SystemRouteName.Build});e.addRoute(i,n.execute)},"registerBuildRoute");So.registerBuildRoute=Fw});var Iu=g(Jr=>{"use strict";Object.defineProperty(Jr,"__esModule",{value:!0});Jr.HTTP_STATUS_TITLES=Jr.HttpStatusCode=void 0;var Mh;(function(e){e[e.CONTINUE=100]="CONTINUE",e[e.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",e[e.PROCESSING=102]="PROCESSING",e[e.EARLY_HINTS=103]="EARLY_HINTS",e[e.OK=200]="OK",e[e.CREATED=201]="CREATED",e[e.ACCEPTED=202]="ACCEPTED",e[e.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",e[e.NO_CONTENT=204]="NO_CONTENT",e[e.RESET_CONTENT=205]="RESET_CONTENT",e[e.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",e[e.MULTI_STATUS=207]="MULTI_STATUS",e[e.ALREADY_REPORTED=208]="ALREADY_REPORTED",e[e.IM_USED=226]="IM_USED",e[e.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",e[e.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",e[e.FOUND=302]="FOUND",e[e.SEE_OTHER=303]="SEE_OTHER",e[e.NOT_MODIFIED=304]="NOT_MODIFIED",e[e.USE_PROXY=305]="USE_PROXY",e[e.SWITCH_PROXY=306]="SWITCH_PROXY",e[e.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",e[e.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",e[e.BAD_REQUEST=400]="BAD_REQUEST",e[e.UNAUTHORIZED=401]="UNAUTHORIZED",e[e.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",e[e.FORBIDDEN=403]="FORBIDDEN",e[e.NOT_FOUND=404]="NOT_FOUND",e[e.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",e[e.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",e[e.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",e[e.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",e[e.CONFLICT=409]="CONFLICT",e[e.GONE=410]="GONE",e[e.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",e[e.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",e[e.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",e[e.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",e[e.URI_TOO_LONG=414]="URI_TOO_LONG",e[e.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",e[e.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",e[e.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",e[e.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",e[e.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",e[e.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",e[e.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",e[e.LOCKED=423]="LOCKED",e[e.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",e[e.TOO_EARLY=425]="TOO_EARLY",e[e.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",e[e.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",e[e.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",e[e.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",e[e.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",e[e.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",e[e.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",e[e.BAD_GATEWAY=502]="BAD_GATEWAY",e[e.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",e[e.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",e[e.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",e[e.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",e[e.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",e[e.LOOP_DETECTED=508]="LOOP_DETECTED",e[e.NOT_EXTENDED=510]="NOT_EXTENDED",e[e.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED"})(Mh||(Jr.HttpStatusCode=Mh={}));Jr.HTTP_STATUS_TITLES={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 Ru=g(Au=>{"use strict";Object.defineProperty(Au,"__esModule",{value:!0});var qw={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"};Au.default=qw});var le=g(zr=>{"use strict";var $w=zr&&zr.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(zr,"__esModule",{value:!0});zr.HttpProblems=void 0;var jw=Zn(),N=Iu(),Vw=$w(Ru()),Gw=ee(),Pu=lo();function Bw(e){return`${new URL(e.url).pathname}`}o(Bw,"instance");function Kw(e,t){let r={timestamp:new Date().toISOString(),requestId:t.requestId,buildId:Gw.Environment.instance.build.BUILD_ID},n=e.headers.get(jw.RAY_ID_HEADER);return n&&(r.rayId=n),r}o(Kw,"trace");var Jw=o((e,t,r,n,i)=>({problem:{type:e.type,title:e.title,status:e.status,detail:e.detail,instance:Bw(t),trace:Kw(t,r),...n},additionalHeaders:i,statusText:Vw.default[e.status]}),"merge"),Ou=class{static{o(this,"HttpProblemsBase")}static format=(t,r,n)=>"problem"in t?Pu.ProblemResponseFormatter.format(t,r,n):Pu.ProblemResponseFormatter.format({problem:t},r,n);static getProblemFromStatus(t,r){return{type:`https://httpproblems.com/http-status/${t}`,status:t,title:N.HTTP_STATUS_TITLES[t],...r}}},Nu=class extends Ou{static{o(this,"HttpProblems")}static#e(t,r,n,i,s){let a=Jw(this.getProblemFromStatus(t),r,n,i,s);return Pu.ProblemResponseFormatter.format(a,r,n)}static continue=(t,r,n,i)=>this.#e(N.HttpStatusCode.OK,t,r,n,i);static switchingProtocols=(t,r,n,i)=>this.#e(N.HttpStatusCode.SWITCHING_PROTOCOLS,t,r,n,i);static processing=(t,r,n,i)=>this.#e(N.HttpStatusCode.PROCESSING,t,r,n,i);static earlyHints=(t,r,n,i)=>this.#e(N.HttpStatusCode.EARLY_HINTS,t,r,n,i);static ok=(t,r,n,i)=>this.#e(N.HttpStatusCode.OK,t,r,n,i);static created=(t,r,n,i)=>this.#e(N.HttpStatusCode.CREATED,t,r,n,i);static accepted=(t,r,n,i)=>this.#e(N.HttpStatusCode.ACCEPTED,t,r,n,i);static nonAuthoritativeInformation=(t,r,n,i)=>this.#e(N.HttpStatusCode.NON_AUTHORITATIVE_INFORMATION,t,r,n,i);static noContent=(t,r,n,i)=>this.#e(N.HttpStatusCode.NO_CONTENT,t,r,n,i);static resetContent=(t,r,n,i)=>this.#e(N.HttpStatusCode.RESET_CONTENT,t,r,n,i);static partialContent=(t,r,n,i)=>this.#e(N.HttpStatusCode.PARTIAL_CONTENT,t,r,n,i);static multiStatus=(t,r,n,i)=>this.#e(N.HttpStatusCode.MULTI_STATUS,t,r,n,i);static alreadyReported=(t,r,n,i)=>this.#e(N.HttpStatusCode.ALREADY_REPORTED,t,r,n,i);static imUsed=(t,r,n,i)=>this.#e(N.HttpStatusCode.IM_USED,t,r,n,i);static multipleChoices=(t,r,n,i)=>this.#e(N.HttpStatusCode.MULTIPLE_CHOICES,t,r,n,i);static movedPermanently=(t,r,n,i)=>this.#e(N.HttpStatusCode.MOVED_PERMANENTLY,t,r,n,i);static found=(t,r,n,i)=>this.#e(N.HttpStatusCode.FOUND,t,r,n,i);static seeOther=(t,r,n,i)=>this.#e(N.HttpStatusCode.SEE_OTHER,t,r,n,i);static notModified=(t,r,n,i)=>this.#e(N.HttpStatusCode.NOT_MODIFIED,t,r,n,i);static useProxy=(t,r,n,i)=>this.#e(N.HttpStatusCode.USE_PROXY,t,r,n,i);static switchProxy=(t,r,n,i)=>this.#e(N.HttpStatusCode.SWITCH_PROXY,t,r,n,i);static temporaryRedirect=(t,r,n,i)=>this.#e(N.HttpStatusCode.TEMPORARY_REDIRECT,t,r,n,i);static permanentRedirect=(t,r,n,i)=>this.#e(N.HttpStatusCode.PERMANENT_REDIRECT,t,r,n,i);static badRequest=(t,r,n,i)=>this.#e(N.HttpStatusCode.BAD_REQUEST,t,r,n,i);static unauthorized=(t,r,n,i)=>this.#e(N.HttpStatusCode.UNAUTHORIZED,t,r,n,i);static paymentRequired=(t,r,n,i)=>this.#e(N.HttpStatusCode.PAYMENT_REQUIRED,t,r,n,i);static forbidden=(t,r,n,i)=>this.#e(N.HttpStatusCode.FORBIDDEN,t,r,n,i);static notFound=(t,r,n,i)=>this.#e(N.HttpStatusCode.NOT_FOUND,t,r,n,i);static methodNotAllowed=(t,r,n,i)=>this.#e(N.HttpStatusCode.METHOD_NOT_ALLOWED,t,r,n,i);static notAcceptable=(t,r,n,i)=>this.#e(N.HttpStatusCode.NOT_ACCEPTABLE,t,r,n,i);static proxyAuthenticationRequired=(t,r,n,i)=>this.#e(N.HttpStatusCode.PROXY_AUTHENTICATION_REQUIRED,t,r,n,i);static requestTimeout=(t,r,n,i)=>this.#e(N.HttpStatusCode.REQUEST_TIMEOUT,t,r,n,i);static conflict=(t,r,n,i)=>this.#e(N.HttpStatusCode.CONFLICT,t,r,n,i);static gone=(t,r,n,i)=>this.#e(N.HttpStatusCode.GONE,t,r,n,i);static lengthRequired=(t,r,n,i)=>this.#e(N.HttpStatusCode.LENGTH_REQUIRED,t,r,n,i);static preconditionFailed=(t,r,n,i)=>this.#e(N.HttpStatusCode.PRECONDITION_FAILED,t,r,n,i);static contentTooLarge=(t,r,n,i)=>this.#e(N.HttpStatusCode.CONTENT_TOO_LARGE,t,r,n,i);static uriTooLong=(t,r,n,i)=>this.#e(N.HttpStatusCode.URI_TOO_LONG,t,r,n,i);static unsupportedMediaType=(t,r,n,i)=>this.#e(N.HttpStatusCode.UNSUPPORTED_MEDIA_TYPE,t,r,n,i);static rangeNotSatisfiable=(t,r,n,i)=>this.#e(N.HttpStatusCode.RANGE_NOT_SATISFIABLE,t,r,n,i);static expectationFailed=(t,r,n,i)=>this.#e(N.HttpStatusCode.EXPECTATION_FAILED,t,r,n,i);static imATeapot=(t,r,n,i)=>this.#e(N.HttpStatusCode.I_AM_A_TEAPOT,t,r,n,i);static misdirectedRequest=(t,r,n,i)=>this.#e(N.HttpStatusCode.MISDIRECTED_REQUEST,t,r,n,i);static unprocessableContent=(t,r,n,i)=>this.#e(N.HttpStatusCode.UNPROCESSABLE_CONTENT,t,r,n,i);static locked=(t,r,n,i)=>this.#e(N.HttpStatusCode.LOCKED,t,r,n,i);static failedDependency=(t,r,n,i)=>this.#e(N.HttpStatusCode.FAILED_DEPENDENCY,t,r,n,i);static tooEarly=(t,r,n,i)=>this.#e(N.HttpStatusCode.TOO_EARLY,t,r,n,i);static upgradeRequired=(t,r,n,i)=>this.#e(N.HttpStatusCode.UPGRADE_REQUIRED,t,r,n,i);static preconditionRequired=(t,r,n,i)=>this.#e(N.HttpStatusCode.PRECONDITION_REQUIRED,t,r,n,i);static tooManyRequests=(t,r,n,i)=>this.#e(N.HttpStatusCode.TOO_MANY_REQUESTS,t,r,n,i);static requestHeaderFieldsTooLarge=(t,r,n,i)=>this.#e(N.HttpStatusCode.REQUEST_HEADER_FIELDS_TOO_LARGE,t,r,n,i);static unavailableForLegalReasons=(t,r,n,i)=>this.#e(N.HttpStatusCode.UNAVAILABLE_FOR_LEGAL_REASONS,t,r,n,i);static internalServerError=(t,r,n,i)=>this.#e(N.HttpStatusCode.INTERNAL_SERVER_ERROR,t,r,n,i);static notImplemented=(t,r,n,i)=>this.#e(N.HttpStatusCode.NOT_IMPLEMENTED,t,r,n,i);static badGateway=(t,r,n,i)=>this.#e(N.HttpStatusCode.BAD_GATEWAY,t,r,n,i);static serviceUnavailable=(t,r,n,i)=>this.#e(N.HttpStatusCode.SERVICE_UNAVAILABLE,t,r,n,i);static gatewayTimeout=(t,r,n,i)=>this.#e(N.HttpStatusCode.GATEWAY_TIMEOUT,t,r,n,i);static httpVersionNotSupported=(t,r,n,i)=>this.#e(N.HttpStatusCode.HTTP_VERSION_NOT_SUPPORTED,t,r,n,i);static variantAlsoNegotiates=(t,r,n,i)=>this.#e(N.HttpStatusCode.VARIANT_ALSO_NEGOTIATES,t,r,n,i);static insufficientStorage=(t,r,n,i)=>this.#e(N.HttpStatusCode.INSUFFICIENT_STORAGE,t,r,n,i);static loopDetected=(t,r,n,i)=>this.#e(N.HttpStatusCode.LOOP_DETECTED,t,r,n,i);static notExtended=(t,r,n,i)=>this.#e(N.HttpStatusCode.NOT_EXTENDED,t,r,n,i);static networkAuthenticationRequired=(t,r,n,i)=>this.#e(N.HttpStatusCode.NETWORK_AUTHENTICATION_REQUIRED,t,r,n,i)};zr.HttpProblems=Nu});var Yt=g(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.isErrorLike=M.withUndefinedAsNull=M.withNullAsUndefined=M.validateConstraint=M.validateConstraints=M.areFunctions=M.isFunction=M.isEmptyObject=M.assertAllDefined=M.assertIsDefined=M.assertType=M.isUndefinedOrNull=M.isDefined=M.isUndefined=M.isBoolean=M.isIterable=M.isNumber=M.isTypedArray=M.isArray=M.isObject=M.getOwnEnumerableKeys=M.isRegexp=M.isStringArray=M.isNonEmptyString=M.isString=M.toString=void 0;var{toString:zw}=Object.prototype,{propertyIsEnumerable:Ww}=Object.prototype;function kh(e){return zw.call(e)}o(kh,"toString");M.toString=kh;function Io(e){return typeof e=="string"}o(Io,"isString");M.isString=Io;function Qw(e){return Io(e)&&e!==""}o(Qw,"isNonEmptyString");M.isNonEmptyString=Qw;function Yw(e){return Array.isArray(e)&&e.every(t=>Io(t))}o(Yw,"isStringArray");M.isStringArray=Yw;function Zw(e){return kh(e)==="[object RegExp]"}o(Zw,"isRegexp");M.isRegexp=Zw;function Xw(e){return[...Object.keys(e),...Object.getOwnPropertySymbols(e).filter(t=>Ww.call(e,t))]}o(Xw,"getOwnEnumerableKeys");M.getOwnEnumerableKeys=Xw;function xu(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&!(e instanceof RegExp)&&!(e instanceof Date)}o(xu,"isObject");M.isObject=xu;function ev(e){return xu(e)&&Array.isArray(e)}o(ev,"isArray");M.isArray=ev;function tv(e){let t=Object.getPrototypeOf(Uint8Array);return typeof e=="object"&&e instanceof t}o(tv,"isTypedArray");M.isTypedArray=tv;function rv(e){return typeof e=="number"&&!isNaN(e)}o(rv,"isNumber");M.isNumber=rv;function nv(e){return!!e&&typeof e[Symbol.iterator]=="function"}o(nv,"isIterable");M.isIterable=nv;function iv(e){return e===!0||e===!1}o(iv,"isBoolean");M.isBoolean=iv;function Hh(e){return typeof e>"u"}o(Hh,"isUndefined");M.isUndefined=Hh;function ov(e){return!ei(e)}o(ov,"isDefined");M.isDefined=ov;function ei(e){return Hh(e)||e===null}o(ei,"isUndefinedOrNull");M.isUndefinedOrNull=ei;function sv(e,t){if(!e)throw new Error(t?`Unexpected type, expected '${t}'`:"Unexpected type")}o(sv,"assertType");M.assertType=sv;function av(e){if(ei(e))throw new Error("Assertion Failed: argument is undefined or null");return e}o(av,"assertIsDefined");M.assertIsDefined=av;function cv(...e){let t=[];for(let r=0;r<e.length;r++){let n=e[r];if(ei(n))throw new Error(`Assertion Failed: argument at index ${r} is undefined or null`);t.push(n)}return t}o(cv,"assertAllDefined");M.assertAllDefined=cv;var uv=Object.prototype.hasOwnProperty;function lv(e){if(!xu(e))return!1;for(let t in e)if(uv.call(e,t))return!1;return!0}o(lv,"isEmptyObject");M.isEmptyObject=lv;function Cu(e){return typeof e=="function"}o(Cu,"isFunction");M.isFunction=Cu;function dv(...e){return e.length>0&&e.every(Cu)}o(dv,"areFunctions");M.areFunctions=dv;function pv(e,t){let r=Math.min(e.length,t.length);for(let n=0;n<r;n++)Fh(e[n],t[n])}o(pv,"validateConstraints");M.validateConstraints=pv;function Fh(e,t){if(Io(t)){if(typeof e!==t)throw new Error(`argument does not match constraint: typeof ${t}`)}else if(Cu(t)){try{if(e instanceof t)return}catch{}if(!ei(e)&&e.constructor===t||t.length===1&&t.call(void 0,e)===!0)return;throw new Error("argument does not match one of these constraints: arg instanceof constraint, arg.constructor === constraint, nor constraint(arg) === true")}}o(Fh,"validateConstraint");M.validateConstraint=Fh;function hv(e){return e===null?void 0:e}o(hv,"withNullAsUndefined");M.withNullAsUndefined=hv;function fv(e){return typeof e>"u"?null:e}o(fv,"withUndefinedAsNull");M.withUndefinedAsNull=fv;function mv(e){return!!e&&typeof e=="object"&&"name"in e&&"message"in e&&"stack"in e}o(mv,"isErrorLike");M.isErrorLike=mv});var ti=g(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.parseValueToBoolean=yt.parseValueToStringArray=yt.getValueFromRequestUser=yt.statusCodesStringToNumberArray=void 0;var Wr=D(),Lu=Yt(),qh=new Map;function yv(e){if(typeof e!="string")throw new Error("Input must be a string");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(e))throw new Error("Malformed input string");let t=qh.get(e);if(t)return t;let r=e.split(","),n=[];for(let i of r){let s=i.split("-");if(s.length===2){let a=parseInt(s[0],10),c=parseInt(s[1],10);for(let u=a;u<=c;u++)n.push(u)}else n.push(parseInt(i,10))}return qh.set(e,n),n}o(yv,"statusCodesStringToNumberArray");yt.statusCodesStringToNumberArray=yv;function gv(e,t,r){if(!t.startsWith("."))throw new Wr.ConfigurationError(`Invalid ${r} - must start with '.' - '${t}' does not`);let n=t.split(".").splice(1),i=e;return n.forEach(s=>{if(i===void 0)throw new Wr.RuntimeError(`Error applying ${r} '${t}', reading '${s}'`);i=i[s]}),`${i}`}o(gv,"getValueFromRequestUser");yt.getValueFromRequestUser=gv;function bv(e){if(Array.isArray(e)){if(e.includes(r=>typeof r!="string"))throw new Wr.ConfigurationError("Received an array that contains non-string values.");return e}if((0,Lu.isString)(e))return e.includes(",")?e.split(",").map(r=>r.trim()).filter(r=>r!==","&&r!==""):[e];throw new Wr.ConfigurationError(`Expected type of string, received type '${typeof e}'`)}o(bv,"parseValueToStringArray");yt.parseValueToStringArray=bv;function _v(e){if((0,Lu.isBoolean)(e))return e;if((0,Lu.isString)(e)){if(e.toLowerCase()==="true")return!0;if(e.toLowerCase()==="false")return!1;throw new Wr.ConfigurationError(`Attempted to parse string to boolean, but received ${e} which cannot be parsed.`)}throw new Wr.ConfigurationError(`Expected type of boolean, received type '${typeof e}'`)}o(_v,"parseValueToBoolean");yt.parseValueToBoolean=_v});var Ro=g(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.generateCorsHeaders=Zt.findMatchingOrigin=Zt.parseCorsPolicies=void 0;var Or=D(),$h=ti(),Ao=Yt();function Ev(e){if(e==null)return[];if(!Array.isArray(e))throw new Or.ConfigurationError(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof e}'`);return e.map(r=>{if(!(0,Ao.isObject)(r))throw new Or.ConfigurationError(`Invalid custom cors policy is set. Expected an object, received '${typeof r}'`);if(!(0,Ao.isNonEmptyString)(r.name))throw new Or.ConfigurationError("Value of 'name' on custom cors policies must be a non-empty string.");if(r.maxAge!==void 0&&!(0,Ao.isNumber)(r.maxAge))throw new Or.ConfigurationError(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof r.maxAge}'`);if(r.allowCredentials!==void 0&&!(0,Ao.isBoolean)(r.allowCredentials))throw new Or.ConfigurationError("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 n=Du(r,"allowedHeaders"),i=Du(r,"allowedMethods"),s=Du(r,"exposeHeaders"),a;try{a=(0,$h.parseValueToStringArray)(r.allowedOrigins)}catch(u){throw new Or.ConfigurationError(`Value of 'allowedOrigins' on custom cors policies is invalid. ${u.message} If using an environment variable, check that it is set correctly.`)}return{name:r.name,allowCredentials:typeof r.allowCredentials=="boolean"?String(r.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:n?n.join(", "):void 0,allowedMethods:i?i.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof r.maxAge=="number"?r.maxAge.toString():void 0}})}o(Ev,"parseCorsPolicies");Zt.parseCorsPolicies=Ev;function Du(e,t){let r;if(e[t]!==void 0)try{r=(0,$h.parseValueToStringArray)(e[t])}catch(n){throw new Or.ConfigurationError(`Value of '${t}' on custom cors policies is invalid. ${n.message} If using an environment variable, check that it is set correctly.`)}return r}o(Du,"parseOptionalProperty");var wv=o((e,t)=>{if(t===null)return;if(e.find(a=>a==="*"))return t;let n=e.map(a=>a.trim().toLowerCase()),i=t.toLowerCase();return n.find(a=>a===i)},"findMatchingOrigin");Zt.findMatchingOrigin=wv;var vv=o((e,t)=>{let r={"access-control-allow-origin":t};e.allowedHeaders&&(r["access-control-allow-headers"]=e.allowedHeaders),e.allowedMethods&&(r["access-control-allow-methods"]=e.allowedMethods),e.exposeHeaders&&(r["access-control-expose-headers"]=e.exposeHeaders);let n=e.allowCredentials;n&&(r["access-control-allow-credentials"]=n);let i=e.maxAge?.toString()??void 0;return i&&(r["access-control-max-age"]=i),r},"generateCorsHeaders");Zt.generateCorsHeaders=vv});var Vh=g(Po=>{"use strict";Object.defineProperty(Po,"__esModule",{value:!0});Po.registerCorsRoute=void 0;var Tv=D(),Sv=Wt(),Uu=le(),Iv=Rr(),Av=Pr(),Rv=mt(),jh=Ro(),Pv=o((e,t)=>{let r=t.routeData.corsPolicies,n=o(async(a,c)=>{let u=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return Uu.HttpProblems.badRequest(a,c,{detail:"Expect headers origin and access-control-request-method"});let y=e.lookup(l,u);if(!y)return Uu.HttpProblems.notFound(a,c);let h=y.routeConfiguration,m=Ov(l,d,p,h,r);return m.isValid?new Response(void 0,{status:200,statusText:"OK",headers:m.headers}):(m.error&&c.log.warn(m.error),Uu.HttpProblems.notFound(a,c))},"optionsHandler"),i=new Sv.Pipeline({processors:[Iv.metricsProcessor],handler:n,gateway:t}),s=new Rv.SystemRouteConfiguration({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:Av.SystemRouteName.CorsPreflight});e.addRoute(s,i.execute)},"registerCorsRoute");Po.registerCorsRoute=Pv;var Ov=o((e,t,r,n,i)=>{let s={isValid:!1,headers:{}};if(n.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":r,"access-control-allow-methods":e,"access-control-allow-headers":t??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(n.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${n.pathPattern}'`};let a=i?.find(l=>l.name===n.corsPolicy);if(!a)throw new Tv.ConfigurationError(`Invalid Configuration - corsPolicy '${n.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let c=(0,jh.findMatchingOrigin)(a.allowedOrigins,r);return c?{isValid:!0,headers:(0,jh.generateCorsHeaders)(a,c)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${r}'`}},"validateAndBuildResponseHeaders")});var Gh=g(Oo=>{"use strict";Object.defineProperty(Oo,"__esModule",{value:!0});Oo.registerNoRoutes=void 0;var Nv=Wt(),xv=Rr(),Cv=Pr(),Lv=mt(),Dv=o((e,t)=>{let r=o(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),n=new Nv.Pipeline({processors:[xv.metricsProcessor],handler:r,gateway:t}),i=new Lv.SystemRouteConfiguration({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:Cv.SystemRouteName.EmptyGatewayCatchall});e.addRoute(i,n.execute)},"registerNoRoutes");Oo.registerNoRoutes=Dv});var Bh=g(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.registerNotMatchedHandler=Nr.notFoundRouteConfiguration=void 0;var Uv=Ir(),Mv=xt(),kv=Wt(),Hv=le(),Fv=Rr(),qv=Pr(),$v=mt();Nr.notFoundRouteConfiguration=new $v.SystemRouteConfiguration({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:qv.SystemRouteName.UnmatchedPath});var jv=o((e,t)=>{let r=o(async(i,s)=>{let a=Mv.runtimeExtensions.value?.notFoundHandler;if(a){let c=Uv.ZuploContextExtensions.getContextExtensions(s);return a(i,s,{routesMatchedByPathOnly:c.pathOnlyMatches??[]})}return Hv.HttpProblems.notFound(i,s)},"notFoundHandler"),n=new kv.Pipeline({processors:[Fv.metricsProcessor],handler:r,gateway:t});e.addRoute(Nr.notFoundRouteConfiguration,n.execute)},"registerNotMatchedHandler");Nr.registerNotMatchedHandler=jv});var Mu=g(No=>{"use strict";Object.defineProperty(No,"__esModule",{value:!0});No.corsProcessor=void 0;var zh=D(),Kh=Ro(),Vv=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Jh=o(e=>{Vv.forEach(t=>e.delete(t))},"stripCorsHeaders"),Gv=o(async(e,t,r,n)=>{let i=t.route;if(!i.corsPolicy||i.corsPolicy==="none"){let d=await n(e),p=new Headers(d.headers);return Jh(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await n(e);if(!(s instanceof Response))throw new zh.SystemError(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=Bv(i,r.routeData.corsPolicies),c=Kv(e,a),u=new Headers(s.headers);return Jh(u),Object.entries(c).forEach(([d,p])=>{u.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:u,webSocket:s.webSocket})},"corsProcessor");No.corsProcessor=Gv;var Bv=o((e,t)=>{if(e.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:e.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let r=t?.find(n=>n.name===e.corsPolicy);if(r===void 0)throw new zh.ConfigurationError(`Invalid Configuration - no corsPolicy '${e.corsPolicy}' found in *.oas.json`);return r},"getCorsPolicy"),Kv=o((e,t)=>{let r=(0,Kh.findMatchingOrigin)(t.allowedOrigins,e.headers.get("origin"));return r?(0,Kh.generateCorsHeaders)(t,r):{}},"getCorsHeaders")});var Wh=g(xo=>{"use strict";Object.defineProperty(xo,"__esModule",{value:!0});xo.registerPingRoute=void 0;var Jv=Wt(),zv=Mu(),Wv=Pr(),Qv=mt(),Yv=o((e,t)=>{let r=o(async()=>new Response(null,{status:200}),"pingRouteHandler"),n=new Jv.Pipeline({processors:[zv.corsProcessor],handler:r,gateway:t}),i=new Qv.SystemRouteConfiguration({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:Wv.SystemRouteName.Ping});e.addRoute(i,n.execute)},"registerPingRoute");xo.registerPingRoute=Yv});var Yh=g(Co=>{"use strict";Object.defineProperty(Co,"__esModule",{value:!0});Co.deepFreeze=void 0;function Qh(e){for(let t in e){let r=e[t];r&&typeof r=="object"&&Qh(r)}return Object.freeze(e)}o(Qh,"deepFreeze");Co.deepFreeze=Qh});var Je=g(Lo=>{"use strict";Object.defineProperty(Lo,"__esModule",{value:!0});Lo.ZuploRequest=void 0;var Zh=Yh(),ku=class e extends Request{static{o(this,"ZuploRequest")}#e=void 0;#t;constructor(t,r){super(t,r);let n=r?.params;n?this.#t=n:t instanceof e?this.#t=t.#t:this.#t={};let i=r?.user;i?this.user=i:t instanceof e&&(this.user=t.user)}get query(){if(this.#e===void 0){let t={},r=new URL(this.url).searchParams;for(let[n,i]of r.entries())t[n]=i;this.#e=t}return(0,Zh.deepFreeze)(this.#e)}get params(){return(0,Zh.deepFreeze)(this.#t)}user};Lo.ZuploRequest=ku});var ri=g(Lt=>{"use strict";Object.defineProperty(Lt,"__esModule",{value:!0});Lt.policyProcessor=Lt.toStackedInboundHandler=Lt.getInboundPolicyHandlerAndOptions=void 0;var Zv=Ir(),Qr=D(),Xh=Je(),Xv=ee();function ef(e,t){let r,n;return Array.isArray(e)?r=e:(r=e.policies?.inbound??[],n=e.path),r.map(s=>{let a=t?.find(u=>u.name===s);if(!a)throw new Qr.ConfigurationError(`Invalid state - no Policy with the name '${s}' ${n&&`on route '${n}'`} was found in the policies configuration (check case).`);let c;if(typeof a.handler?.module=="object"&&(c=a.handler?.module[a.handler.export]),typeof c!="function")throw new Qr.ConfigurationError(`Invalid state - invalid handler on policy '${s}' ${n&&`on route '${n}'`}. Expected a function, received '${typeof c}'`);return{exportName:a.handler.export,handler:c,options:a.handler.options,policyName:a.name}})}o(ef,"getInboundPolicyHandlerAndOptions");Lt.getInboundPolicyHandlerAndOptions=ef;function eT(e,t){return(e.policies?.outbound??[]).map(i=>{let s=t?.find(c=>c.name===i);if(!s)throw new Qr.ConfigurationError(`Invalid state - no Policy with the name '${i}' on route '${e.path}' was found in the policies configuration (check case).`);let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new Qr.ConfigurationError(`Invalid state - invalid handler on policy '${i}' on route '${e.path}'`);return{exportName:s.handler.export,handler:a,options:s.handler.options,policyName:s.name}})}o(eT,"getOutboundPolicyHandlerAndOptions");var tT=o(e=>async(t,r)=>{let n=Zv.ZuploContextExtensions.getContextExtensions(r),i=[...e],s=t;for(;i.length>0;){let a=i.shift();if(!a)return s;let c=await a.handler(s,r,a.options,a.policyName);if(c instanceof Xh.ZuploRequest)s=c;else if(c instanceof Request)s=new Xh.ZuploRequest(c);else{if(c instanceof Response)return c;throw new Qr.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an inbound policy must be a Response or Request.`)}n.latestRequest=s}return s},"toStackedInboundHandler");Lt.toStackedInboundHandler=tT;var rT=o(e=>async(t,r,n)=>{let i=[...e],s=t;for(;i.length>0;){let a=i.shift();if(!a)return s;let c=await a.handler(s,r,n,a.options,a.policyName);if(!(c instanceof Response))throw new Qr.ConfigurationError(`Invalid state - invalid handler on policy '${a.policyName}'${a.routeName?` on route '${a.routeName}`:""}. The result of an outbound policy must be a Response.`);s=c}return s},"toStackedOutboundHandler"),nT=o(async(e,t,r,n)=>{let i=ef(t.route,r.routeData.policies),s=eT(t.route,r.routeData.policies),a=(0,Lt.toStackedInboundHandler)(i);try{let c=await a(e,t);if(c instanceof Response)return c;let u=await n(c),l=rT(s),d;return Xv.Environment.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(u,e,t):d=u.ok?l(u,e,t):u,d}catch(c){return t.log.error(c),r.errorHandler(e,t,c)}},"policyProcessor");Lt.policyProcessor=nT});var tf=g(Yr=>{"use strict";Object.defineProperty(Yr,"__esModule",{value:!0});Yr.serialize=Yr.parse=void 0;var iT=Object.prototype.toString,Do=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/;function oT(e,t){if(typeof e!="string")throw new TypeError("argument str must be a string");let r={},i=(t||{}).decode||aT,s=0;for(;s<e.length;){let a=e.indexOf("=",s);if(a===-1)break;let c=e.indexOf(";",s);if(c===-1)c=e.length;else if(c<a){s=e.lastIndexOf(";",a-1)+1;continue}let u=e.slice(s,a).trim();if(r[u]===void 0){let l=e.slice(a+1,c).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),r[u]=lT(l,i)}s=c+1}return r}o(oT,"parse");Yr.parse=oT;function sT(e,t,r){let n=r||{},i=n.encode||cT;if(typeof i!="function")throw new TypeError("option encode is invalid");if(!Do.test(e))throw new TypeError("argument name is invalid");let s=i(t);if(s&&!Do.test(s))throw new TypeError("argument val is invalid");let a=e+"="+s;if(n.maxAge!=null){let c=n.maxAge-0;if(isNaN(c)||!isFinite(c))throw new TypeError("option maxAge is invalid");a+="; Max-Age="+Math.floor(c)}if(n.domain){if(!Do.test(n.domain))throw new TypeError("option domain is invalid");a+="; Domain="+n.domain}if(n.path){if(!Do.test(n.path))throw new TypeError("option path is invalid");a+="; Path="+n.path}if(n.expires){let c=n.expires;if(!uT(c)||isNaN(c.valueOf()))throw new TypeError("option expires is invalid");a+="; Expires="+c.toUTCString()}if(n.httpOnly&&(a+="; HttpOnly"),n.secure&&(a+="; Secure"),n.priority)switch(typeof n.priority=="string"?n.priority.toLowerCase():n.priority){case"low":a+="; Priority=Low";break;case"medium":a+="; Priority=Medium";break;case"high":a+="; Priority=High";break;default:throw new TypeError("option priority is invalid")}if(n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:a+="; SameSite=Strict";break;case"lax":a+="; SameSite=Lax";break;case"strict":a+="; SameSite=Strict";break;case"none":a+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return a}o(sT,"serialize");Yr.serialize=sT;function aT(e){return e.indexOf("%")!==-1?decodeURIComponent(e):e}o(aT,"decode");function cT(e){return encodeURIComponent(e)}o(cT,"encode");function uT(e){return iT.call(e)==="[object Date]"||e instanceof Date}o(uT,"isDate");function lT(e,t){try{return t(e)}catch{return e}}o(lT,"tryDecode")});var rf=g(Uo=>{"use strict";Object.defineProperty(Uo,"__esModule",{value:!0});Uo.devPortalBaseURL=void 0;var dT=tf();function pT(e,t){try{let r=/v\d+(-\d+)?/g,i=(0,dT.parse)(t.get("Cookie")||"")["zp-dev-portal"];return i!==null&&i&&r.test(i)?`https://dev-portal-${i}.zuplo.com`:e}catch{}return e}o(pT,"devPortalBaseURL");Uo.devPortalBaseURL=pT});var cf=g(Zr=>{"use strict";Object.defineProperty(Zr,"__esModule",{value:!0});Zr.registerDevPortalLegacyRedirectRoute=Zr.registerDevPortalV3Route=void 0;var Hu=Ct(),of=Wt(),sf=Rr(),hT=ri(),af=mt(),fT=rf(),Xt=ee(),nf="/__zuplo/dev-portal",mT="dev-portal-id",yT="dev-portal-host",gT="zp-account",bT="zp-project",_T="dev-portal-build",ET=`
36
36
  <!DOCTYPE html>
37
37
  <html lang="en">
38
38
  <head>
@@ -46,7 +46,7 @@
46
46
  <p>For more information, see <a href="https://zuplo.com/docs/articles/developer-portal">https://zuplo.com/docs/articles/developer-portal</a>.</p>
47
47
  </body>
48
48
  </html>
49
- `,wT=o((e,t)=>{let{sitePathname:r}=t.runtimeSettings.developerPortal,n=Xt.Environment.instance.deploymentName,i=Xt.Environment.instance.devPortalBaseUrl,s=o(async(u,l)=>{if(Xt.Environment.instance.isLocalDevelopment)return new Response(ET,{headers:{"content-type":"text/html"}});if(!n)return Hu.HttpProblems.internalServerError(u,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(u.url),p=(0,fT.devPortalBaseURL)(i,u.headers),y=new URL(`${d.pathname}${d.search}`,p),{headers:h,method:m,body:v}=u;return Xt.Environment.instance.build.ACCOUNT_NAME&&h.set(gT,Xt.Environment.instance.build.ACCOUNT_NAME),Xt.Environment.instance.build.PROJECT_NAME&&h.set(bT,Xt.Environment.instance.build.PROJECT_NAME),h.set(mT,n),h.set(yT,d.host),h.set(_T,Xt.Environment.instance.build.BUILD_ID),await fetch(y.toString(),{headers:h,method:m,body:v,redirect:"manual"})},"devPortalRoute"),a=new of.Pipeline([sf.metricsProcessor,hT.policyProcessor],s,t),c=new af.SystemRouteConfiguration({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${r}|/_next)(.*)`,systemRouteName:Hu.SystemRouteName.DeveloperPortal});e.addRoute(c,a.execute)},"registerDevPortalV3Route");Zr.registerDevPortalV3Route=wT;var vT=o((e,t)=>{let{sitePathname:r}=t.runtimeSettings.developerPortal,n=o(async a=>{let c=new URL(a.url);return c.pathname=`${r}${c.pathname.substring(nf.length)}`,Response.redirect(c.toString(),302)},"devPortalRedirectRoute"),i=new of.Pipeline([sf.metricsProcessor],n,t),s=new af.SystemRouteConfiguration({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${nf}(.*)`,systemRouteName:Hu.SystemRouteName.DeveloperPortalLegacy});e.addRoute(s,i.execute)},"registerDevPortalLegacyRedirectRoute");Zr.registerDevPortalLegacyRedirectRoute=vT});var Fu=g(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.API_KEY=Xr.SYSTEM_LOGGER=void 0;Xr.SYSTEM_LOGGER="system-logger";Xr.API_KEY="api-key"});var uf=g(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.CoreLogger=void 0;var qu=0,$u=class{static{o(this,"CoreLogger")}constructor(t,r,n,i,s){this.#r=r,this.#n=n??"local",this.#i=i,this.#o=s,this.#e(t)}#e=t=>{let r=["error","warn","info","debug"],n=!1,i=o(()=>{},"emptyFunction"),s=o((a,c)=>{this.#o.forEach(u=>{u.log(a,c)})},"pushFunction");r.forEach(a=>{this.#t[a]=n?i:s,a==t&&(n=!0)})};#t={};#r;#n;#i;#o;log(t,r,n,i,s,a){qu>=Number.MAX_SAFE_INTEGER&&(qu=0);let c={requestId:n,rayId:i,level:t,logSource:r,messages:s,timestamp:new Date,logOwner:this.#r,loggingId:this.#n,buildId:this.#i,vectorClock:qu++};this.#t[t](c,a)}};Mo.CoreLogger=$u});var Dt=g(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.LogPlugin=void 0;var TT=xt(),ju=class extends TT.RuntimePlugin{static{o(this,"LogPlugin")}};ko.LogPlugin=ju});var lf=g(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.LoggingContext=void 0;var Vu=class{static{o(this,"LoggingContext")}constructor(t,r,n){this.#e=t,this.custom=r,this.originalRequest=n}#e;custom;originalRequest;waitUntil=t=>{this.#e.waitUntil(t)}};Ho.LoggingContext=Vu});var df=g(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.RequestLogger=void 0;var Gu=class{static{o(this,"RequestLogger")}constructor(t,r,n,i){this.#t=t,this.#r=r,this.#n=n,this.#i=i}#e="request";#t;#r;#n;#i;debug=(...t)=>{this.#n.log("debug",this.#e,this.#t,this.#r,t,this.#i)};info=(...t)=>{this.#n.log("info",this.#e,this.#t,this.#r,t,this.#i)};log=(...t)=>{this.#n.log("info",this.#e,this.#t,this.#r,t,this.#i)};warn=(...t)=>{this.#n.log("warn",this.#e,this.#t,this.#r,t,this.#i)};error=(...t)=>{this.#n.log("error",this.#e,this.#t,this.#r,t,this.#i)}};Fo.RequestLogger=Gu});var xr=g(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.cleanStack=er.serializeError=er.NonError=void 0;var pf=Yt(),ST=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(e=>[e.name,e]),IT=new Map(ST),Bu=class e extends Error{static{o(this,"NonError")}name="NonError";constructor(t){super(e._prepareSuperMessage(t))}static _prepareSuperMessage(t){try{return JSON.stringify(t)}catch{return String(t)}}};er.NonError=Bu;var AT=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Ku=Symbol(".toJSON was called"),RT=o(e=>{e[Ku]=!0;let t=e.toJSON();return delete e[Ku],t},"toJSON"),PT=o(e=>IT.get(e)??Error,"getErrorConstructor"),hf=o(({from:e,seen:t,to:r,forceEnumerable:n,maxDepth:i,depth:s,useToJSON:a,serialize:c})=>{if(!r)if(Array.isArray(e))r=[];else if(!c&&(0,pf.isErrorLike)(e)){let l=PT(e.name);r=new l}else r={};if(t.push(e),s>=i)return r;if(a&&typeof e.toJSON=="function"&&e[Ku]!==!0)return RT(e);let u=o(l=>hf({from:l,seen:[...t],forceEnumerable:n,maxDepth:i,depth:s,useToJSON:a,serialize:c}),"continueDestroyCircular");for(let[l,d]of Object.entries(e)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){r[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){r[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){r[l]=d;continue}if(!t.includes(e[l])){s++,r[l]=u(e[l]);continue}r[l]="[Circular]"}}for(let{property:l,enumerable:d}of AT)typeof e[l]<"u"&&e[l]!==null&&Object.defineProperty(r,l,{value:(0,pf.isErrorLike)(e[l])?u(e[l]):e[l],enumerable:n?!0:d,configurable:!0,writable:!0});return r},"destroyCircular");function OT(e,t){let r=t?.maxDepth??Number.POSITIVE_INFINITY,n=t?.useToJSON??!0;return typeof e=="object"&&e!==null?hf({from:e,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:n,serialize:!0}):typeof e=="function"?`[Function: ${e.name??"anonymous"}]`:e}o(OT,"serializeError");er.serializeError=OT;var NT=/file:\/\/\/(.*?)\/dist\//g,xT=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,CT="at async Event.respondWith";function LT(e){return typeof e!="string"?e:e.split(`
49
+ `,wT=o((e,t)=>{let{sitePathname:r}=t.runtimeSettings.developerPortal,n=Xt.Environment.instance.deploymentName,i=Xt.Environment.instance.devPortalBaseUrl,s=o(async(u,l)=>{if(Xt.Environment.instance.isLocalDevelopment)return new Response(ET,{headers:{"content-type":"text/html"}});if(!n)return Hu.HttpProblems.internalServerError(u,l,{detail:"Unable to retrieve deployment name. Please contact support for assistance."});let d=new URL(u.url),p=(0,fT.devPortalBaseURL)(i,u.headers),y=new URL(`${d.pathname}${d.search}`,p),{headers:h,method:m,body:v}=u;return Xt.Environment.instance.build.ACCOUNT_NAME&&h.set(gT,Xt.Environment.instance.build.ACCOUNT_NAME),Xt.Environment.instance.build.PROJECT_NAME&&h.set(bT,Xt.Environment.instance.build.PROJECT_NAME),h.set(mT,n),h.set(yT,d.host),h.set(_T,Xt.Environment.instance.build.BUILD_ID),await fetch(y.toString(),{headers:h,method:m,body:v,redirect:"manual"})},"devPortalRoute"),a=new of.Pipeline({processors:[sf.metricsProcessor,hT.policyProcessor],handler:s,gateway:t}),c=new af.SystemRouteConfiguration({label:"SYSTEM_API_DOCS_V3_ROUTE",methods:["GET","PUT","POST","DELETE","PATCH","HEAD"],path:`(${r}|/_next)(.*)`,systemRouteName:Hu.SystemRouteName.DeveloperPortal});e.addRoute(c,a.execute)},"registerDevPortalV3Route");Zr.registerDevPortalV3Route=wT;var vT=o((e,t)=>{let{sitePathname:r}=t.runtimeSettings.developerPortal,n=o(async a=>{let c=new URL(a.url);return c.pathname=`${r}${c.pathname.substring(nf.length)}`,Response.redirect(c.toString(),302)},"devPortalRedirectRoute"),i=new of.Pipeline({processors:[sf.metricsProcessor],handler:n,gateway:t}),s=new af.SystemRouteConfiguration({label:"SYSTEM_API_DOCS_REDIRECT_ROUTE",methods:["GET"],path:`${nf}(.*)`,systemRouteName:Hu.SystemRouteName.DeveloperPortalLegacy});e.addRoute(s,i.execute)},"registerDevPortalLegacyRedirectRoute");Zr.registerDevPortalLegacyRedirectRoute=vT});var Fu=g(Xr=>{"use strict";Object.defineProperty(Xr,"__esModule",{value:!0});Xr.API_KEY=Xr.SYSTEM_LOGGER=void 0;Xr.SYSTEM_LOGGER="system-logger";Xr.API_KEY="api-key"});var uf=g(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.CoreLogger=void 0;var qu=0,$u=class{static{o(this,"CoreLogger")}constructor(t,r,n,i,s){this.#r=r,this.#n=n??"local",this.#i=i,this.#o=s,this.#e(t)}#e=t=>{let r=["error","warn","info","debug"],n=!1,i=o(()=>{},"emptyFunction"),s=o((a,c)=>{this.#o.forEach(u=>{u.log(a,c)})},"pushFunction");r.forEach(a=>{this.#t[a]=n?i:s,a==t&&(n=!0)})};#t={};#r;#n;#i;#o;log(t,r,n,i,s,a){qu>=Number.MAX_SAFE_INTEGER&&(qu=0);let c={requestId:n,rayId:i,level:t,logSource:r,messages:s,timestamp:new Date,logOwner:this.#r,loggingId:this.#n,buildId:this.#i,vectorClock:qu++};this.#t[t](c,a)}};Mo.CoreLogger=$u});var Dt=g(ko=>{"use strict";Object.defineProperty(ko,"__esModule",{value:!0});ko.LogPlugin=void 0;var TT=xt(),ju=class extends TT.RuntimePlugin{static{o(this,"LogPlugin")}};ko.LogPlugin=ju});var lf=g(Ho=>{"use strict";Object.defineProperty(Ho,"__esModule",{value:!0});Ho.LoggingContext=void 0;var Vu=class{static{o(this,"LoggingContext")}constructor(t,r,n){this.#e=t,this.custom=r,this.originalRequest=n}#e;custom;originalRequest;waitUntil=t=>{this.#e.waitUntil(t)}};Ho.LoggingContext=Vu});var df=g(Fo=>{"use strict";Object.defineProperty(Fo,"__esModule",{value:!0});Fo.RequestLogger=void 0;var Gu=class{static{o(this,"RequestLogger")}constructor(t,r,n,i){this.#t=t,this.#r=r,this.#n=n,this.#i=i}#e="request";#t;#r;#n;#i;debug=(...t)=>{this.#n.log("debug",this.#e,this.#t,this.#r,t,this.#i)};info=(...t)=>{this.#n.log("info",this.#e,this.#t,this.#r,t,this.#i)};log=(...t)=>{this.#n.log("info",this.#e,this.#t,this.#r,t,this.#i)};warn=(...t)=>{this.#n.log("warn",this.#e,this.#t,this.#r,t,this.#i)};error=(...t)=>{this.#n.log("error",this.#e,this.#t,this.#r,t,this.#i)}};Fo.RequestLogger=Gu});var xr=g(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.cleanStack=er.serializeError=er.NonError=void 0;var pf=Yt(),ST=[EvalError,RangeError,ReferenceError,SyntaxError,TypeError,URIError].filter(Boolean).map(e=>[e.name,e]),IT=new Map(ST),Bu=class e extends Error{static{o(this,"NonError")}name="NonError";constructor(t){super(e._prepareSuperMessage(t))}static _prepareSuperMessage(t){try{return JSON.stringify(t)}catch{return String(t)}}};er.NonError=Bu;var AT=[{property:"name",enumerable:!1},{property:"message",enumerable:!1},{property:"stack",enumerable:!1},{property:"code",enumerable:!0},{property:"cause",enumerable:!1}],Ku=Symbol(".toJSON was called"),RT=o(e=>{e[Ku]=!0;let t=e.toJSON();return delete e[Ku],t},"toJSON"),PT=o(e=>IT.get(e)??Error,"getErrorConstructor"),hf=o(({from:e,seen:t,to:r,forceEnumerable:n,maxDepth:i,depth:s,useToJSON:a,serialize:c})=>{if(!r)if(Array.isArray(e))r=[];else if(!c&&(0,pf.isErrorLike)(e)){let l=PT(e.name);r=new l}else r={};if(t.push(e),s>=i)return r;if(a&&typeof e.toJSON=="function"&&e[Ku]!==!0)return RT(e);let u=o(l=>hf({from:l,seen:[...t],forceEnumerable:n,maxDepth:i,depth:s,useToJSON:a,serialize:c}),"continueDestroyCircular");for(let[l,d]of Object.entries(e)){if(typeof Buffer=="function"&&Buffer.isBuffer(d)){r[l]="[object Buffer]";continue}if(d!==null&&typeof d=="object"&&typeof d.pipe=="function"){r[l]="[object Stream]";continue}if(typeof d!="function"){if(!d||typeof d!="object"){r[l]=d;continue}if(!t.includes(e[l])){s++,r[l]=u(e[l]);continue}r[l]="[Circular]"}}for(let{property:l,enumerable:d}of AT)typeof e[l]<"u"&&e[l]!==null&&Object.defineProperty(r,l,{value:(0,pf.isErrorLike)(e[l])?u(e[l]):e[l],enumerable:n?!0:d,configurable:!0,writable:!0});return r},"destroyCircular");function OT(e,t){let r=t?.maxDepth??Number.POSITIVE_INFINITY,n=t?.useToJSON??!0;return typeof e=="object"&&e!==null?hf({from:e,seen:[],forceEnumerable:!0,maxDepth:r,depth:0,useToJSON:n,serialize:!0}):typeof e=="function"?`[Function: ${e.name??"anonymous"}]`:e}o(OT,"serializeError");er.serializeError=OT;var NT=/file:\/\/\/(.*?)\/dist\//g,xT=/\(https:\/\/raw\.githubusercontent\.com\/.*?\)/g,CT="at async Event.respondWith";function LT(e){return typeof e!="string"?e:e.split(`
50
50
  `).filter(t=>!t.trim().startsWith("at async file")).map((t,r)=>{let n=t.replaceAll(NT,"").replaceAll(xT,"").replaceAll(CT,"").trim();return r===0||n.length===0?n:` ${n}`}).filter(t=>t.length>0).join(`
51
51
  `)}o(LT,"cleanStack");er.cleanStack=LT});var ff=g(zu=>{"use strict";Object.defineProperty(zu,"__esModule",{value:!0});var Ju=Yt();function DT(e,t,r=""){let n=[],i=t?.maxDepth??3;return o(function s(a,c={},u,l){let d=c.indent||" ",p;c.inlineCharacterLimit===void 0?p={newline:`
52
52
  `,newlineOrSpace:`
@@ -56,7 +56,7 @@
56
56
  `)}o(HT,"messagesToMultilineText");Fe.messagesToMultilineText=HT;function gf(e){return typeof e=="string"?e:JSON.stringify(e)}o(gf,"stringifyNonString");Fe.stringifyNonString=gf;function bf(e){return typeof e=="string"?e:e===null?"null":typeof e>"u"?"undefined":typeof e=="number"||typeof e=="boolean"||typeof e=="bigint"||typeof e=="symbol"?e.toString():typeof e=="function"?`[function ${e.name}]`:typeof e=="object"&&Array.isArray(e)?`[array ${e.length}]`:e instanceof Error?`${e.name??"Error"}: ${e.message??"unknown"}`:typeof e=="object"?(0,yf.toString)(e):"unknown"}o(bf,"stringifyNonStringToText");Fe.stringifyNonStringToText=bf});var U,ae,Ie=I(()=>{U=crypto,ae=o(e=>e instanceof CryptoKey,"isCryptoKey")});var FT,qo,Qu=I(()=>{Ie();FT=o(async(e,t)=>{let r=`SHA-${e.slice(-3)}`;return new Uint8Array(await U.subtle.digest(r,t))},"digest"),qo=FT});function Ae(...e){let t=e.reduce((i,{length:s})=>i+s,0),r=new Uint8Array(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r}function _f(e,t){return Ae(Y.encode(e),new Uint8Array([0]),t)}function Yu(e,t,r){if(t<0||t>=$o)throw new RangeError(`value must be >= 0 and <= ${$o-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],r)}function jo(e){let t=Math.floor(e/$o),r=e%$o,n=new Uint8Array(8);return Yu(n,t,0),Yu(n,r,4),n}function Vo(e){let t=new Uint8Array(4);return Yu(t,e),t}function Go(e){return Ae(Vo(e.length),e)}async function Ef(e,t,r){let n=Math.ceil((t>>3)/32),i=new Uint8Array(n*32);for(let s=0;s<n;s++){let a=new Uint8Array(4+e.length+r.length);a.set(Vo(s+1)),a.set(e,4),a.set(r,4+e.length),i.set(await qo("sha256",a),s*32)}return i.slice(0,t>>3)}var Y,ue,$o,_e=I(()=>{Qu();Y=new TextEncoder,ue=new TextDecoder,$o=2**32;o(Ae,"concat");o(_f,"p2s");o(Yu,"writeUInt32BE");o(jo,"uint64be");o(Vo,"uint32be");o(Go,"lengthAndInput");o(Ef,"concatKdf")});var Bo,Z,Zu,te,Re=I(()=>{_e();Bo=o(e=>{let t=e;typeof t=="string"&&(t=Y.encode(t));let r=32768,n=[];for(let i=0;i<t.length;i+=r)n.push(String.fromCharCode.apply(null,t.subarray(i,i+r)));return btoa(n.join(""))},"encodeBase64"),Z=o(e=>Bo(e).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),"encode"),Zu=o(e=>{let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r},"decodeBase64"),te=o(e=>{let t=e;t instanceof Uint8Array&&(t=ue.decode(t)),t=t.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return Zu(t)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}},"decode")});var Xu={};Wi(Xu,{JOSEAlgNotAllowed:()=>tr,JOSEError:()=>me,JOSENotSupported:()=>k,JWEDecryptionFailed:()=>Ut,JWEInvalid:()=>R,JWKInvalid:()=>ni,JWKSInvalid:()=>rr,JWKSMultipleMatchingKeys:()=>ii,JWKSNoMatchingKey:()=>Cr,JWKSTimeout:()=>oi,JWSInvalid:()=>z,JWSSignatureVerificationFailed:()=>Lr,JWTClaimValidationFailed:()=>Ee,JWTExpired:()=>en,JWTInvalid:()=>pe});var me,Ee,en,tr,k,Ut,R,z,pe,ni,rr,Cr,ii,oi,Lr,V=I(()=>{me=class extends Error{static{o(this,"JOSEError")}static get code(){return"ERR_JOSE_GENERIC"}constructor(t){var r;super(t),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(r=Error.captureStackTrace)===null||r===void 0||r.call(Error,this,this.constructor)}},Ee=class extends me{static{o(this,"JWTClaimValidationFailed")}static get code(){return"ERR_JWT_CLAIM_VALIDATION_FAILED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=r,this.reason=n}},en=class extends me{static{o(this,"JWTExpired")}static get code(){return"ERR_JWT_EXPIRED"}constructor(t,r="unspecified",n="unspecified"){super(t),this.code="ERR_JWT_EXPIRED",this.claim=r,this.reason=n}},tr=class extends me{static{o(this,"JOSEAlgNotAllowed")}constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}static get code(){return"ERR_JOSE_ALG_NOT_ALLOWED"}},k=class extends me{static{o(this,"JOSENotSupported")}constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}static get code(){return"ERR_JOSE_NOT_SUPPORTED"}},Ut=class extends me{static{o(this,"JWEDecryptionFailed")}constructor(){super(...arguments),this.code="ERR_JWE_DECRYPTION_FAILED",this.message="decryption operation failed"}static get code(){return"ERR_JWE_DECRYPTION_FAILED"}},R=class extends me{static{o(this,"JWEInvalid")}constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}static get code(){return"ERR_JWE_INVALID"}},z=class extends me{static{o(this,"JWSInvalid")}constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}static get code(){return"ERR_JWS_INVALID"}},pe=class extends me{static{o(this,"JWTInvalid")}constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}static get code(){return"ERR_JWT_INVALID"}},ni=class extends me{static{o(this,"JWKInvalid")}constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}static get code(){return"ERR_JWK_INVALID"}},rr=class extends me{static{o(this,"JWKSInvalid")}constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}static get code(){return"ERR_JWKS_INVALID"}},Cr=class extends me{static{o(this,"JWKSNoMatchingKey")}constructor(){super(...arguments),this.code="ERR_JWKS_NO_MATCHING_KEY",this.message="no applicable key found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_NO_MATCHING_KEY"}},ii=class extends me{static{o(this,"JWKSMultipleMatchingKeys")}constructor(){super(...arguments),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS",this.message="multiple matching keys found in the JSON Web Key Set"}static get code(){return"ERR_JWKS_MULTIPLE_MATCHING_KEYS"}},oi=class extends me{static{o(this,"JWKSTimeout")}constructor(){super(...arguments),this.code="ERR_JWKS_TIMEOUT",this.message="request timed out"}static get code(){return"ERR_JWKS_TIMEOUT"}},Lr=class extends me{static{o(this,"JWSSignatureVerificationFailed")}constructor(){super(...arguments),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED",this.message="signature verification failed"}static get code(){return"ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}});var nr,si=I(()=>{Ie();nr=U.getRandomValues.bind(U)});function el(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new k(`Unsupported JWE Algorithm: ${e}`)}}var Ko,Jo=I(()=>{V();si();o(el,"bitLength");Ko=o(e=>nr(new Uint8Array(el(e)>>3)),"default")});var qT,zo,tl=I(()=>{V();Jo();qT=o((e,t)=>{if(t.length<<3!==el(e))throw new R("Invalid Initialization Vector length")},"checkIvLength"),zo=qT});var $T,tn,rl=I(()=>{V();$T=o((e,t)=>{let r=e.byteLength<<3;if(r!==t)throw new R(`Invalid Content Encryption Key length. Expected ${t} bits, got ${r} bits`)},"checkCekLength"),tn=$T});var jT,vf,Tf=I(()=>{jT=o((e,t)=>{if(!(e instanceof Uint8Array))throw new TypeError("First argument must be a buffer");if(!(t instanceof Uint8Array))throw new TypeError("Second argument must be a buffer");if(e.length!==t.length)throw new TypeError("Input buffers must have the same length");let r=e.length,n=0,i=-1;for(;++i<r;)n|=e[i]^t[i];return n===0},"timingSafeEqual"),vf=jT});function Pe(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function ir(e,t){return e.name===t}function Wo(e){return parseInt(e.name.slice(4),10)}function VT(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Sf(e,t){if(t.length&&!t.some(r=>e.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let n=t.pop();r+=`one of ${t.join(", ")}, or ${n}.`}else t.length===2?r+=`one of ${t[0]} or ${t[1]}.`:r+=`${t[0]}.`;throw new TypeError(r)}}function If(e,t,...r){switch(t){case"HS256":case"HS384":case"HS512":{if(!ir(e.algorithm,"HMAC"))throw Pe("HMAC");let n=parseInt(t.slice(2),10);if(Wo(e.algorithm.hash)!==n)throw Pe(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!ir(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Pe("RSASSA-PKCS1-v1_5");let n=parseInt(t.slice(2),10);if(Wo(e.algorithm.hash)!==n)throw Pe(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!ir(e.algorithm,"RSA-PSS"))throw Pe("RSA-PSS");let n=parseInt(t.slice(2),10);if(Wo(e.algorithm.hash)!==n)throw Pe(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw Pe("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!ir(e.algorithm,"ECDSA"))throw Pe("ECDSA");let n=VT(t);if(e.algorithm.namedCurve!==n)throw Pe(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Sf(e,r)}function qe(e,t,...r){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!ir(e.algorithm,"AES-GCM"))throw Pe("AES-GCM");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw Pe(n,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!ir(e.algorithm,"AES-KW"))throw Pe("AES-KW");let n=parseInt(t.slice(1,4),10);if(e.algorithm.length!==n)throw Pe(n,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw Pe("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!ir(e.algorithm,"PBKDF2"))throw Pe("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!ir(e.algorithm,"RSA-OAEP"))throw Pe("RSA-OAEP");let n=parseInt(t.slice(9),10)||1;if(Wo(e.algorithm.hash)!==n)throw Pe(`SHA-${n}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}Sf(e,r)}var or=I(()=>{o(Pe,"unusable");o(ir,"isAlgorithm");o(Wo,"getHashLength");o(VT,"getNamedCurve");o(Sf,"checkUsage");o(If,"checkSigCryptoKey");o(qe,"checkEncCryptoKey")});function Af(e,t,...r){if(r.length>2){let n=r.pop();e+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?e+=`one of type ${r[0]} or ${r[1]}.`:e+=`of type ${r[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor&&t.constructor.name&&(e+=` Received an instance of ${t.constructor.name}`),e}function nl(e,t,...r){return Af(`Key for the ${e} algorithm must be `,t,...r)}var oe,st=I(()=>{o(Af,"message");oe=o((e,...t)=>Af("Key must be ",e,...t),"default");o(nl,"withAlg")});var il,W,at=I(()=>{Ie();il=o(e=>ae(e),"default"),W=["CryptoKey"]});async function GT(e,t,r,n,i,s){if(!(t instanceof Uint8Array))throw new TypeError(oe(t,"Uint8Array"));let a=parseInt(e.slice(1,4),10),c=await U.subtle.importKey("raw",t.subarray(a>>3),"AES-CBC",!1,["decrypt"]),u=await U.subtle.importKey("raw",t.subarray(0,a>>3),{hash:`SHA-${a<<1}`,name:"HMAC"},!1,["sign"]),l=Ae(s,n,r,jo(s.length<<3)),d=new Uint8Array((await U.subtle.sign("HMAC",u,l)).slice(0,a>>3)),p;try{p=vf(i,d)}catch{}if(!p)throw new Ut;let y;try{y=new Uint8Array(await U.subtle.decrypt({iv:n,name:"AES-CBC"},c,r))}catch{}if(!y)throw new Ut;return y}async function BT(e,t,r,n,i,s){let a;t instanceof Uint8Array?a=await U.subtle.importKey("raw",t,"AES-GCM",!1,["decrypt"]):(qe(t,e,"decrypt"),a=t);try{return new Uint8Array(await U.subtle.decrypt({additionalData:s,iv:n,name:"AES-GCM",tagLength:128},a,Ae(r,i)))}catch{throw new Ut}}var KT,Qo,ol=I(()=>{_e();tl();rl();Tf();V();Ie();or();st();at();o(GT,"cbcDecrypt");o(BT,"gcmDecrypt");KT=o(async(e,t,r,n,i,s)=>{if(!ae(t)&&!(t instanceof Uint8Array))throw new TypeError(oe(t,...W,"Uint8Array"));switch(zo(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return t instanceof Uint8Array&&tn(t,parseInt(e.slice(-3),10)),GT(e,t,r,n,i,s);case"A128GCM":case"A192GCM":case"A256GCM":return t instanceof Uint8Array&&tn(t,parseInt(e.slice(1,4),10)),BT(e,t,r,n,i,s);default:throw new k("Unsupported JWE Content Encryption Algorithm")}},"decrypt"),Qo=KT});var Rf,Pf,sl=I(()=>{V();Rf=o(async()=>{throw new k('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `inflateRaw` decrypt option to provide Inflate Raw implementation.')},"inflate"),Pf=o(async()=>{throw new k('JWE "zip" (Compression Algorithm) Header Parameter is not supported by your javascript runtime. You need to use the `deflateRaw` encrypt option to provide Deflate Raw implementation.')},"deflate")});var JT,bt,rn=I(()=>{JT=o((...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let r;for(let n of t){let i=Object.keys(n);if(!r||r.size===0){r=new Set(i);continue}for(let s of i){if(r.has(s))return!1;r.add(s)}}return!0},"isDisjoint"),bt=JT});function zT(e){return typeof e=="object"&&e!==null}function Q(e){if(!zT(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}var $e=I(()=>{o(zT,"isObjectLike");o(Q,"isObject")});var WT,nn,al=I(()=>{WT=[{hash:"SHA-256",name:"HMAC"},!0,["sign"]],nn=WT});function Of(e,t){if(e.algorithm.length!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function Nf(e,t,r){if(ae(e))return qe(e,t,r),e;if(e instanceof Uint8Array)return U.subtle.importKey("raw",e,"AES-KW",!0,[r]);throw new TypeError(oe(e,...W,"Uint8Array"))}var ai,ci,Yo=I(()=>{al();Ie();or();st();at();o(Of,"checkKeySize");o(Nf,"getCryptoKey");ai=o(async(e,t,r)=>{let n=await Nf(t,e,"wrapKey");Of(n,e);let i=await U.subtle.importKey("raw",r,...nn);return new Uint8Array(await U.subtle.wrapKey("raw",i,n,"AES-KW"))},"wrap"),ci=o(async(e,t,r)=>{let n=await Nf(t,e,"unwrapKey");Of(n,e);let i=await U.subtle.unwrapKey("raw",r,n,"AES-KW",...nn);return new Uint8Array(await U.subtle.exportKey("raw",i))},"unwrap")});async function Zo(e,t,r,n,i=new Uint8Array(0),s=new Uint8Array(0)){if(!ae(e))throw new TypeError(oe(e,...W));if(qe(e,"ECDH"),!ae(t))throw new TypeError(oe(t,...W));qe(t,"ECDH","deriveBits");let a=Ae(Go(Y.encode(r)),Go(i),Go(s),Vo(n)),c;e.algorithm.name==="X25519"?c=256:e.algorithm.name==="X448"?c=448:c=Math.ceil(parseInt(e.algorithm.namedCurve.substr(-3),10)/8)<<3;let u=new Uint8Array(await U.subtle.deriveBits({name:e.algorithm.name,public:e},t,c));return Ef(u,n,a)}async function xf(e){if(!ae(e))throw new TypeError(oe(e,...W));return U.subtle.generateKey(e.algorithm,!0,["deriveBits"])}function Xo(e){if(!ae(e))throw new TypeError(oe(e,...W));return["P-256","P-384","P-521"].includes(e.algorithm.namedCurve)||e.algorithm.name==="X25519"||e.algorithm.name==="X448"}var cl=I(()=>{_e();Ie();or();st();at();o(Zo,"deriveKey");o(xf,"generateEpk");o(Xo,"ecdhAllowed")});function ul(e){if(!(e instanceof Uint8Array)||e.length<8)throw new R("PBES2 Salt Input must be 8 or more octets")}var Lf=I(()=>{V();o(ul,"checkP2s")});function QT(e,t){if(e instanceof Uint8Array)return U.subtle.importKey("raw",e,"PBKDF2",!1,["deriveBits"]);if(ae(e))return qe(e,t,"deriveBits","deriveKey"),e;throw new TypeError(oe(e,...W,"Uint8Array"))}async function Df(e,t,r,n){ul(e);let i=_f(t,e),s=parseInt(t.slice(13,16),10),a={hash:`SHA-${t.slice(8,11)}`,iterations:r,name:"PBKDF2",salt:i},c={length:s,name:"AES-KW"},u=await QT(n,t);if(u.usages.includes("deriveBits"))return new Uint8Array(await U.subtle.deriveBits(a,u,s));if(u.usages.includes("deriveKey"))return U.subtle.deriveKey(a,u,c,!1,["wrapKey","unwrapKey"]);throw new TypeError('PBKDF2 key "usages" must include "deriveBits" or "deriveKey"')}var Uf,Mf,ll=I(()=>{si();_e();Re();Yo();Lf();Ie();or();st();at();o(QT,"getCryptoKey");o(Df,"deriveKey");Uf=o(async(e,t,r,n=2048,i=nr(new Uint8Array(16)))=>{let s=await Df(i,e,n,t);return{encryptedKey:await ai(e.slice(-6),s,r),p2c:n,p2s:Z(i)}},"encrypt"),Mf=o(async(e,t,r,n,i)=>{let s=await Df(i,e,n,t);return ci(e.slice(-6),s,r)},"decrypt")});function on(e){switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return"RSA-OAEP";default:throw new k(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var kf=I(()=>{V();o(on,"subtleRsaEs")});var Dr,es=I(()=>{Dr=o((e,t)=>{if(e.startsWith("RS")||e.startsWith("PS")){let{modulusLength:r}=t.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${e} requires key modulusLength to be 2048 bits or larger`)}},"default")});var Hf,Ff,dl=I(()=>{kf();al();Ie();or();es();st();at();Hf=o(async(e,t,r)=>{if(!ae(t))throw new TypeError(oe(t,...W));if(qe(t,e,"encrypt","wrapKey"),Dr(e,t),t.usages.includes("encrypt"))return new Uint8Array(await U.subtle.encrypt(on(e),t,r));if(t.usages.includes("wrapKey")){let n=await U.subtle.importKey("raw",r,...nn);return new Uint8Array(await U.subtle.wrapKey("raw",n,t,on(e)))}throw new TypeError('RSA-OAEP key "usages" must include "encrypt" or "wrapKey" for this operation')},"encrypt"),Ff=o(async(e,t,r)=>{if(!ae(t))throw new TypeError(oe(t,...W));if(qe(t,e,"decrypt","unwrapKey"),Dr(e,t),t.usages.includes("decrypt"))return new Uint8Array(await U.subtle.decrypt(on(e),t,r));if(t.usages.includes("unwrapKey")){let n=await U.subtle.unwrapKey("raw",r,t,on(e),...nn);return new Uint8Array(await U.subtle.exportKey("raw",n))}throw new TypeError('RSA-OAEP key "usages" must include "decrypt" or "unwrapKey" for this operation')},"decrypt")});function ui(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new k(`Unsupported JWE Algorithm: ${e}`)}}var _t,li=I(()=>{V();si();o(ui,"bitLength");_t=o(e=>nr(new Uint8Array(ui(e)>>3)),"default")});var pl,qf=I(()=>{pl=o((e,t)=>{let r=(e.match(/.{1,64}/g)||[]).join(`
57
57
  `);return`-----BEGIN ${t}-----
58
58
  ${r}
59
- -----END ${t}-----`},"default")});function jf(e){let t=[],r=0;for(;r<e.length;){let n=zf(e.subarray(r));t.push(n),r+=n.byteLength}return t}function zf(e){let t=0,r=e[0]&31;if(t++,r===31){for(r=0;e[t]>=128;)r=r*128+e[t]-128,t++;r=r*128+e[t]-128,t++}let n=0;if(e[t]<128)n=e[t],t++;else if(n===128){for(n=0;e[t+n]!==0||e[t+n+1]!==0;){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++}let s=t+n+2;return{byteLength:s,contents:e.subarray(t,t+n),raw:e.subarray(0,s)}}else{let s=e[t]&127;t++,n=0;for(let a=0;a<s;a++)n=n*256+e[t],t++}let i=t+n;return{byteLength:i,contents:e.subarray(t,i),raw:e.subarray(0,i)}}function YT(e){let t=jf(jf(zf(e).contents)[0].contents);return Bo(t[t[0].raw[0]===160?6:5].raw)}function ZT(e){let t=e.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=Zu(t);return pl(YT(r),"PUBLIC KEY")}var Vf,Gf,Bf,sr,$f,Kf,Jf,hl,Wf,ts=I(()=>{Ie();st();Re();qf();V();at();Vf=o(async(e,t,r)=>{if(!ae(r))throw new TypeError(oe(r,...W));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return pl(Bo(new Uint8Array(await U.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},"genericExport"),Gf=o(e=>Vf("public","spki",e),"toSPKI"),Bf=o(e=>Vf("private","pkcs8",e),"toPKCS8"),sr=o((e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return!1;let i=e.subarray(n,n+t.length);return i.length!==t.length?!1:i.every((s,a)=>s===t[a])||sr(e,t,n+1)},"findOid"),$f=o(e=>{switch(!0){case sr(e,[42,134,72,206,61,3,1,7]):return"P-256";case sr(e,[43,129,4,0,34]):return"P-384";case sr(e,[43,129,4,0,35]):return"P-521";case sr(e,[43,101,110]):return"X25519";case sr(e,[43,101,111]):return"X448";case sr(e,[43,101,112]):return"Ed25519";case sr(e,[43,101,113]):return"Ed448";default:throw new k("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},"getNamedCurve"),Kf=o(async(e,t,r,n,i)=>{var s;let a,c,u=new Uint8Array(atob(r.replace(e,"")).split("").map(d=>d.charCodeAt(0))),l=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},c=l?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},c=l?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},c=l?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},c=l?["verify"]:["sign"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},c=l?["verify"]:["sign"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},c=l?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let d=$f(u);a=d.startsWith("P-")?{name:"ECDH",namedCurve:d}:{name:d},c=l?[]:["deriveBits"];break}case"EdDSA":a={name:$f(u)},c=l?["verify"]:["sign"];break;default:throw new k('Invalid or unsupported "alg" (Algorithm) value')}return U.subtle.importKey(t,u,a,(s=i?.extractable)!==null&&s!==void 0?s:!1,c)},"genericImport"),Jf=o((e,t,r)=>Kf(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),"fromPKCS8"),hl=o((e,t,r)=>Kf(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r),"fromSPKI");o(jf,"getElement");o(zf,"parseElement");o(YT,"spkiFromX509");o(ZT,"getSPKI");Wf=o((e,t,r)=>{let n;try{n=ZT(e)}catch(i){throw new TypeError("failed to parse the X.509 certificate",{cause:i})}return hl(n,t,r)},"fromX509")});function XT(e){let t,r;switch(e.kty){case"oct":{switch(e.alg){case"HS256":case"HS384":case"HS512":t={name:"HMAC",hash:`SHA-${e.alg.slice(-3)}`},r=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new k(`${e.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":t={name:"AES-GCM"},r=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":t={name:"AES-KW"},r=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":t={name:"PBKDF2"},r=["deriveBits"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new k('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}var eS,fl,Qf=I(()=>{Ie();V();Re();o(XT,"subtleMapping");eS=o(async e=>{var t,r;if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:n,keyUsages:i}=XT(e),s=[n,(t=e.ext)!==null&&t!==void 0?t:!1,(r=e.key_ops)!==null&&r!==void 0?r:i];if(n.name==="PBKDF2")return U.subtle.importKey("raw",te(e.k),...s);let a={...e};return delete a.alg,delete a.use,U.subtle.importKey("jwk",a,...s)},"parse"),fl=eS});async function Yf(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return hl(e,t,r)}async function Zf(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Wf(e,t,r)}async function Xf(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Jf(e,t,r)}async function ar(e,t,r){var n;if(!Q(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return r??(r=e.ext!==!0),r?fl({...e,alg:t,ext:(n=e.ext)!==null&&n!==void 0?n:!1}):te(e.k);case"RSA":if(e.oth!==void 0)throw new k('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return fl({...e,alg:t});default:throw new k('Unsupported "kty" (Key Type) Parameter value')}}var di=I(()=>{Re();ts();Qf();V();$e();o(Yf,"importSPKI");o(Zf,"importX509");o(Xf,"importPKCS8");o(ar,"importJWK")});var tS,rS,nS,cr,pi=I(()=>{st();at();tS=o((e,t)=>{if(!(t instanceof Uint8Array)){if(!il(t))throw new TypeError(nl(e,t,...W,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${W.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},"symmetricTypeCheck"),rS=o((e,t,r)=>{if(!il(t))throw new TypeError(nl(e,t,...W));if(t.type==="secret")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},"asymmetricTypeCheck"),nS=o((e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?tS(e,t):rS(e,t,r)},"checkKeyType"),cr=nS});async function iS(e,t,r,n,i){if(!(r instanceof Uint8Array))throw new TypeError(oe(r,"Uint8Array"));let s=parseInt(e.slice(1,4),10),a=await U.subtle.importKey("raw",r.subarray(s>>3),"AES-CBC",!1,["encrypt"]),c=await U.subtle.importKey("raw",r.subarray(0,s>>3),{hash:`SHA-${s<<1}`,name:"HMAC"},!1,["sign"]),u=new Uint8Array(await U.subtle.encrypt({iv:n,name:"AES-CBC"},a,t)),l=Ae(i,n,u,jo(i.length<<3)),d=new Uint8Array((await U.subtle.sign("HMAC",c,l)).slice(0,s>>3));return{ciphertext:u,tag:d}}async function oS(e,t,r,n,i){let s;r instanceof Uint8Array?s=await U.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(qe(r,e,"encrypt"),s=r);let a=new Uint8Array(await U.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},s,t)),c=a.slice(-16);return{ciphertext:a.slice(0,-16),tag:c}}var sS,hi,ml=I(()=>{_e();tl();rl();Ie();or();st();V();at();o(iS,"cbcEncrypt");o(oS,"gcmEncrypt");sS=o(async(e,t,r,n,i)=>{if(!ae(r)&&!(r instanceof Uint8Array))throw new TypeError(oe(r,...W,"Uint8Array"));switch(zo(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&tn(r,parseInt(e.slice(-3),10)),iS(e,t,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&tn(r,parseInt(e.slice(1,4),10)),oS(e,t,r,n,i);default:throw new k("Unsupported JWE Content Encryption Algorithm")}},"encrypt"),hi=sS});async function em(e,t,r,n){let i=e.slice(0,7);n||(n=Ko(i));let{ciphertext:s,tag:a}=await hi(i,r,t,n,new Uint8Array(0));return{encryptedKey:s,iv:Z(n),tag:Z(a)}}async function tm(e,t,r,n,i){let s=e.slice(0,7);return Qo(s,t,r,n,i,new Uint8Array(0))}var yl=I(()=>{ml();ol();Jo();Re();o(em,"wrap");o(tm,"unwrap")});async function aS(e,t,r,n,i){switch(cr(e,t,"decrypt"),e){case"dir":{if(r!==void 0)throw new R("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new R("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Q(n.epk))throw new R('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Xo(t))throw new k("ECDH with the provided key is not allowed or not supported by your javascript runtime");let s=await ar(n.epk,e),a,c;if(n.apu!==void 0){if(typeof n.apu!="string")throw new R('JOSE Header "apu" (Agreement PartyUInfo) invalid');a=te(n.apu)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new R('JOSE Header "apv" (Agreement PartyVInfo) invalid');c=te(n.apv)}let u=await Zo(s,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?ui(n.enc):parseInt(e.slice(-5,-2),10),a,c);if(e==="ECDH-ES")return u;if(r===void 0)throw new R("JWE Encrypted Key missing");return ci(e.slice(-6),u,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new R("JWE Encrypted Key missing");return Ff(e,t,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new R("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new R('JOSE Header "p2c" (PBES2 Count) missing or invalid');let s=i?.maxPBES2Count||1e4;if(n.p2c>s)throw new R('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new R('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return Mf(e,t,r,n.p2c,te(n.p2s))}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new R("JWE Encrypted Key missing");return ci(e,t,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new R("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new R('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new R('JOSE Header "tag" (Authentication Tag) missing or invalid');let s=te(n.iv),a=te(n.tag);return tm(e,t,r,s,a)}default:throw new k('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var rm,nm=I(()=>{Yo();cl();ll();dl();Re();V();li();di();pi();$e();yl();o(aS,"decryptKeyManagement");rm=aS});function cS(e,t,r,n,i){if(i.crit!==void 0&&n.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...t.entries()]):s=t;for(let a of n.crit){if(!s.has(a))throw new k(`Extension Header Parameter "${a}" is not recognized`);if(i[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(s.get(a)&&n[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}var Et,sn=I(()=>{V();o(cS,"validateCrit");Et=cS});var uS,fi,gl=I(()=>{uS=o((e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)},"validateAlgorithms"),fi=uS});async function an(e,t,r){var n;if(!Q(e))throw new R("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new R("JOSE Header missing");if(typeof e.iv!="string")throw new R("JWE Initialization Vector missing or incorrect type");if(typeof e.ciphertext!="string")throw new R("JWE Ciphertext missing or incorrect type");if(typeof e.tag!="string")throw new R("JWE Authentication Tag missing or incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new R("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new R("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new R("JWE AAD incorrect type");if(e.header!==void 0&&!Q(e.header))throw new R("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!Q(e.unprotected))throw new R("JWE Per-Recipient Unprotected Header incorrect type");let i;if(e.protected)try{let j=te(e.protected);i=JSON.parse(ue.decode(j))}catch{throw new R("JWE Protected Header is invalid")}if(!bt(i,e.header,e.unprotected))throw new R("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let s={...i,...e.header,...e.unprotected};if(Et(R,new Map,r?.crit,i,s),s.zip!==void 0){if(!i||!i.zip)throw new R('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(s.zip!=="DEF")throw new k('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:a,enc:c}=s;if(typeof a!="string"||!a)throw new R("missing JWE Algorithm (alg) in JWE Header");if(typeof c!="string"||!c)throw new R("missing JWE Encryption Algorithm (enc) in JWE Header");let u=r&&fi("keyManagementAlgorithms",r.keyManagementAlgorithms),l=r&&fi("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(u&&!u.has(a))throw new tr('"alg" (Algorithm) Header Parameter not allowed');if(l&&!l.has(c))throw new tr('"enc" (Encryption Algorithm) Header Parameter not allowed');let d;e.encrypted_key!==void 0&&(d=te(e.encrypted_key));let p=!1;typeof t=="function"&&(t=await t(i,e),p=!0);let y;try{y=await rm(a,t,d,s,r)}catch(j){if(j instanceof TypeError||j instanceof R||j instanceof k)throw j;y=_t(c)}let h=te(e.iv),m=te(e.tag),v=Y.encode((n=e.protected)!==null&&n!==void 0?n:""),T;e.aad!==void 0?T=Ae(v,Y.encode("."),Y.encode(e.aad)):T=v;let S=await Qo(c,y,te(e.ciphertext),h,m,T);s.zip==="DEF"&&(S=await(r?.inflateRaw||Rf)(S));let O={plaintext:S};return e.protected!==void 0&&(O.protectedHeader=i),e.aad!==void 0&&(O.additionalAuthenticatedData=te(e.aad)),e.unprotected!==void 0&&(O.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(O.unprotectedHeader=e.header),p?{...O,key:t}:O}var rs=I(()=>{Re();ol();sl();V();rn();$e();nm();_e();li();sn();gl();o(an,"flattenedDecrypt")});async function ns(e,t,r){if(e instanceof Uint8Array&&(e=ue.decode(e)),typeof e!="string")throw new R("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:s,3:a,4:c,length:u}=e.split(".");if(u!==5)throw new R("Invalid Compact JWE");let l=await an({ciphertext:a,iv:s||void 0,protected:n||void 0,tag:c||void 0,encrypted_key:i||void 0},t,r),d={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return typeof t=="function"?{...d,key:l.key}:d}var bl=I(()=>{rs();V();_e();o(ns,"compactDecrypt")});async function im(e,t,r){if(!Q(e))throw new R("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(Q))throw new R("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new R("JWE Recipients has no members");for(let n of e.recipients)try{return await an({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch{}throw new Ut}var om=I(()=>{rs();V();$e();o(im,"generalDecrypt")});var lS,sm,am=I(()=>{Ie();st();Re();at();lS=o(async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:Z(e)};if(!ae(e))throw new TypeError(oe(e,...W,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:i,...s}=await U.subtle.exportKey("jwk",e);return s},"keyToJWK"),sm=lS});async function cm(e){return Gf(e)}async function um(e){return Bf(e)}async function is(e){return sm(e)}var _l=I(()=>{ts();ts();am();o(cm,"exportSPKI");o(um,"exportPKCS8");o(is,"exportJWK")});async function dS(e,t,r,n,i={}){let s,a,c;switch(cr(e,r,"encrypt"),e){case"dir":{c=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Xo(r))throw new k("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:u,apv:l}=i,{epk:d}=i;d||(d=(await xf(r)).privateKey);let{x:p,y,crv:h,kty:m}=await is(d),v=await Zo(r,d,e==="ECDH-ES"?t:e,e==="ECDH-ES"?ui(t):parseInt(e.slice(-5,-2),10),u,l);if(a={epk:{x:p,crv:h,kty:m}},m==="EC"&&(a.epk.y=y),u&&(a.apu=Z(u)),l&&(a.apv=Z(l)),e==="ECDH-ES"){c=v;break}c=n||_t(t);let T=e.slice(-6);s=await ai(T,v,c);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{c=n||_t(t),s=await Hf(e,r,c);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{c=n||_t(t);let{p2c:u,p2s:l}=i;({encryptedKey:s,...a}=await Uf(e,r,c,u,l));break}case"A128KW":case"A192KW":case"A256KW":{c=n||_t(t),s=await ai(e,r,c);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{c=n||_t(t);let{iv:u}=i;({encryptedKey:s,...a}=await em(e,r,c,u));break}default:throw new k('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:c,encryptedKey:s,parameters:a}}var os,El=I(()=>{Yo();cl();ll();dl();Re();li();V();_l();pi();yl();o(dS,"encryptKeyManagement");os=dS});var wl,Mt,ss=I(()=>{Re();ml();sl();Jo();El();V();rn();_e();sn();wl=Symbol(),Mt=class{static{o(this,"FlattenedEncrypt")}constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new R("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!bt(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new R("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(Et(R,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0){if(!this._protectedHeader||!this._protectedHeader.zip)throw new R('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(n.zip!=="DEF")throw new k('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:i,enc:s}=n;if(typeof i!="string"||!i)throw new R('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof s!="string"||!s)throw new R('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let a;if(i==="dir"){if(this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if(i==="ECDH-ES"&&this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");let c;{let m;({cek:c,encryptedKey:a,parameters:m}=await os(i,s,t,this._cek,this._keyManagementParameters)),m&&(r&&wl in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...m}:this.setUnprotectedHeader(m):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...m}:this.setProtectedHeader(m))}this._iv||(this._iv=Ko(s));let u,l,d;this._protectedHeader?l=Y.encode(Z(JSON.stringify(this._protectedHeader))):l=Y.encode(""),this._aad?(d=Z(this._aad),u=Ae(l,Y.encode("."),Y.encode(d))):u=l;let p,y;if(n.zip==="DEF"){let m=await(r?.deflateRaw||Pf)(this._plaintext);({ciphertext:p,tag:y}=await hi(s,m,c,this._iv,u))}else({ciphertext:p,tag:y}=await hi(s,this._plaintext,c,this._iv,u));let h={ciphertext:Z(p),iv:Z(this._iv),tag:Z(y)};return a&&(h.encrypted_key=Z(a)),d&&(h.aad=d),this._protectedHeader&&(h.protected=ue.decode(l)),this._sharedUnprotectedHeader&&(h.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(h.header=this._unprotectedHeader),h}}});var vl,as,lm=I(()=>{ss();V();li();rn();El();Re();sn();vl=class{static{o(this,"IndividualRecipient")}constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},as=class{static{o(this,"GeneralEncrypt")}constructor(t){this._recipients=[],this._plaintext=t}addRecipient(t,r){let n=new vl(this,t,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(t){var r,n,i;if(!this._recipients.length)throw new R("at least one recipient must be added");if(t={deflateRaw:t?.deflateRaw},this._recipients.length===1){let[u]=this._recipients,l=await new Mt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(u.unprotectedHeader).encrypt(u.key,{...u.options,...t}),d={ciphertext:l.ciphertext,iv:l.iv,recipients:[{}],tag:l.tag};return l.aad&&(d.aad=l.aad),l.protected&&(d.protected=l.protected),l.unprotected&&(d.unprotected=l.unprotected),l.encrypted_key&&(d.recipients[0].encrypted_key=l.encrypted_key),l.header&&(d.recipients[0].header=l.header),d}let s;for(let u=0;u<this._recipients.length;u++){let l=this._recipients[u];if(!bt(this._protectedHeader,this._unprotectedHeader,l.unprotectedHeader))throw new R("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let d={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader},{alg:p}=d;if(typeof p!="string"||!p)throw new R('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(p==="dir"||p==="ECDH-ES")throw new R('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof d.enc!="string"||!d.enc)throw new R('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!s)s=d.enc;else if(s!==d.enc)throw new R('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if(Et(R,new Map,l.options.crit,this._protectedHeader,d),d.zip!==void 0&&(!this._protectedHeader||!this._protectedHeader.zip))throw new R('JWE "zip" (Compression Algorithm) Header MUST be integrity protected')}let a=_t(s),c={ciphertext:"",iv:"",recipients:[],tag:""};for(let u=0;u<this._recipients.length;u++){let l=this._recipients[u],d={};c.recipients.push(d);let y={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader}.alg.startsWith("PBES2")?2048+u:void 0;if(u===0){let v=await new Mt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(a).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(l.unprotectedHeader).setKeyManagementParameters({p2c:y}).encrypt(l.key,{...l.options,...t,[wl]:!0});c.ciphertext=v.ciphertext,c.iv=v.iv,c.tag=v.tag,v.aad&&(c.aad=v.aad),v.protected&&(c.protected=v.protected),v.unprotected&&(c.unprotected=v.unprotected),d.encrypted_key=v.encrypted_key,v.header&&(d.header=v.header);continue}let{encryptedKey:h,parameters:m}=await os(((r=l.unprotectedHeader)===null||r===void 0?void 0:r.alg)||((n=this._protectedHeader)===null||n===void 0?void 0:n.alg)||((i=this._unprotectedHeader)===null||i===void 0?void 0:i.alg),s,l.key,a,{p2c:y});d.encrypted_key=Z(h),(l.unprotectedHeader||m)&&(d.header={...l.unprotectedHeader,...m})}return c}}});function mi(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new k(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Tl=I(()=>{V();o(mi,"subtleDsa")});function yi(e,t,r){if(ae(t))return If(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(oe(t,...W));return U.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(oe(t,...W,"Uint8Array"))}var Sl=I(()=>{Ie();or();st();at();o(yi,"getCryptoKey")});var pS,dm,pm=I(()=>{Tl();Ie();es();Sl();pS=o(async(e,t,r,n)=>{let i=await yi(e,t,"verify");Dr(e,i);let s=mi(e,i.algorithm);try{return await U.subtle.verify(s,i,r,n)}catch{return!1}},"verify"),dm=pS});async function cn(e,t,r){var n;if(!Q(e))throw new z("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new z('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new z("JWS Protected Header incorrect type");if(e.payload===void 0)throw new z("JWS Payload missing");if(typeof e.signature!="string")throw new z("JWS Signature missing or incorrect type");if(e.header!==void 0&&!Q(e.header))throw new z("JWS Unprotected Header incorrect type");let i={};if(e.protected)try{let T=te(e.protected);i=JSON.parse(ue.decode(T))}catch{throw new z("JWS Protected Header is invalid")}if(!bt(i,e.header))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let s={...i,...e.header},a=Et(z,new Map([["b64",!0]]),r?.crit,i,s),c=!0;if(a.has("b64")&&(c=i.b64,typeof c!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:u}=s;if(typeof u!="string"||!u)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=r&&fi("algorithms",r.algorithms);if(l&&!l.has(u))throw new tr('"alg" (Algorithm) Header Parameter not allowed');if(c){if(typeof e.payload!="string")throw new z("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new z("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"&&(t=await t(i,e),d=!0),cr(u,t,"verify");let p=Ae(Y.encode((n=e.protected)!==null&&n!==void 0?n:""),Y.encode("."),typeof e.payload=="string"?Y.encode(e.payload):e.payload),y=te(e.signature);if(!await dm(u,t,y,p))throw new Lr;let m;c?m=te(e.payload):typeof e.payload=="string"?m=Y.encode(e.payload):m=e.payload;let v={payload:m};return e.protected!==void 0&&(v.protectedHeader=i),e.header!==void 0&&(v.unprotectedHeader=e.header),d?{...v,key:t}:v}var cs=I(()=>{Re();pm();V();_e();rn();$e();pi();sn();gl();o(cn,"flattenedVerify")});async function us(e,t,r){if(e instanceof Uint8Array&&(e=ue.decode(e)),typeof e!="string")throw new z("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:s,length:a}=e.split(".");if(a!==3)throw new z("Invalid Compact JWS");let c=await cn({payload:i,protected:n,signature:s},t,r),u={payload:c.payload,protectedHeader:c.protectedHeader};return typeof t=="function"?{...u,key:c.key}:u}var Il=I(()=>{cs();V();_e();o(us,"compactVerify")});async function hm(e,t,r){if(!Q(e))throw new z("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(Q))throw new z("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await cn({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new Lr}var fm=I(()=>{cs();V();$e();o(hm,"generalVerify")});var un,Al=I(()=>{un=o(e=>Math.floor(e.getTime()/1e3),"default")});var hS,ln,Rl=I(()=>{hS=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,ln=o(e=>{let t=hS.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}},"default")});var mm,fS,dn,ls=I(()=>{V();_e();Al();Rl();$e();mm=o(e=>e.toLowerCase().replace(/^application\//,""),"normalizeTyp"),fS=o((e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,"checkAudiencePresence"),dn=o((e,t,r={})=>{let{typ:n}=r;if(n&&(typeof e.typ!="string"||mm(e.typ)!==mm(n)))throw new Ee('unexpected "typ" JWT header value',"typ","check_failed");let i;try{i=JSON.parse(ue.decode(t))}catch{}if(!Q(i))throw new pe("JWT Claims Set must be a top-level JSON object");let{requiredClaims:s=[],issuer:a,subject:c,audience:u,maxTokenAge:l}=r;l!==void 0&&s.push("iat"),u!==void 0&&s.push("aud"),c!==void 0&&s.push("sub"),a!==void 0&&s.push("iss");for(let h of new Set(s.reverse()))if(!(h in i))throw new Ee(`missing required "${h}" claim`,h,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(i.iss))throw new Ee('unexpected "iss" claim value',"iss","check_failed");if(c&&i.sub!==c)throw new Ee('unexpected "sub" claim value',"sub","check_failed");if(u&&!fS(i.aud,typeof u=="string"?[u]:u))throw new Ee('unexpected "aud" claim value',"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=ln(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,y=un(p||new Date);if((i.iat!==void 0||l)&&typeof i.iat!="number")throw new Ee('"iat" claim must be a number',"iat","invalid");if(i.nbf!==void 0){if(typeof i.nbf!="number")throw new Ee('"nbf" claim must be a number',"nbf","invalid");if(i.nbf>y+d)throw new Ee('"nbf" claim timestamp check failed',"nbf","check_failed")}if(i.exp!==void 0){if(typeof i.exp!="number")throw new Ee('"exp" claim must be a number',"exp","invalid");if(i.exp<=y-d)throw new en('"exp" claim timestamp check failed',"exp","check_failed")}if(l){let h=y-i.iat,m=typeof l=="number"?l:ln(l);if(h-d>m)throw new en('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(h<0-d)throw new Ee('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return i},"default")});async function ym(e,t,r){var n;let i=await us(e,t,r);if(!((n=i.protectedHeader.crit)===null||n===void 0)&&n.includes("b64")&&i.protectedHeader.b64===!1)throw new pe("JWTs MUST NOT use unencoded payload");let a={payload:dn(i.protectedHeader,i.payload,r),protectedHeader:i.protectedHeader};return typeof t=="function"?{...a,key:i.key}:a}var gm=I(()=>{Il();ls();V();o(ym,"jwtVerify")});async function bm(e,t,r){let n=await ns(e,t,r),i=dn(n.protectedHeader,n.plaintext,r),{protectedHeader:s}=n;if(s.iss!==void 0&&s.iss!==i.iss)throw new Ee('replicated "iss" claim header parameter mismatch',"iss","mismatch");if(s.sub!==void 0&&s.sub!==i.sub)throw new Ee('replicated "sub" claim header parameter mismatch',"sub","mismatch");if(s.aud!==void 0&&JSON.stringify(s.aud)!==JSON.stringify(i.aud))throw new Ee('replicated "aud" claim header parameter mismatch',"aud","mismatch");let a={payload:i,protectedHeader:s};return typeof t=="function"?{...a,key:n.key}:a}var _m=I(()=>{bl();ls();V();o(bm,"jwtDecrypt")});var pn,Pl=I(()=>{ss();pn=class{static{o(this,"CompactEncrypt")}constructor(t){this._flattened=new Mt(t)}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this._flattened.encrypt(t,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var mS,Em,wm=I(()=>{Tl();Ie();es();Sl();mS=o(async(e,t,r)=>{let n=await yi(e,t,"sign");Dr(e,n);let i=await U.subtle.sign(mi(e,n.algorithm),n,r);return new Uint8Array(i)},"sign"),Em=mS});var ur,ds=I(()=>{Re();wm();rn();V();_e();pi();sn();ur=class{static{o(this,"FlattenedSign")}constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new z("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!bt(this._protectedHeader,this._unprotectedHeader))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},i=Et(z,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),s=!0;if(i.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=n;if(typeof a!="string"||!a)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');cr(a,t,"sign");let c=this._payload;s&&(c=Y.encode(Z(c)));let u;this._protectedHeader?u=Y.encode(Z(JSON.stringify(this._protectedHeader))):u=Y.encode("");let l=Ae(u,Y.encode("."),c),d=await Em(a,t,l),p={signature:Z(d),payload:""};return s&&(p.payload=ue.decode(c)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=ue.decode(u)),p}}});var hn,Ol=I(()=>{ds();hn=class{static{o(this,"CompactSign")}constructor(t){this._flattened=new ur(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}});var Nl,ps,vm=I(()=>{ds();V();Nl=class{static{o(this,"IndividualSignature")}constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},ps=class{static{o(this,"GeneralSign")}constructor(t){this._signatures=[],this._payload=t}addSignature(t,r){let n=new Nl(this,t,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new z("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r<this._signatures.length;r++){let n=this._signatures[r],i=new ur(this._payload);i.setProtectedHeader(n.protectedHeader),i.setUnprotectedHeader(n.unprotectedHeader);let{payload:s,...a}=await i.sign(n.key,n.options);if(r===0)t.payload=s;else if(t.payload!==s)throw new z("inconsistent use of JWS Unencoded Payload (RFC7797)");t.signatures.push(a)}return t}}});var lr,hs=I(()=>{Al();$e();Rl();lr=class{static{o(this,"ProduceJWT")}constructor(t){if(!Q(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:t}:this._payload={...this._payload,nbf:un(new Date)+ln(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:t}:this._payload={...this._payload,exp:un(new Date)+ln(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:un(new Date)}:this._payload={...this._payload,iat:t},this}}});var fs,Tm=I(()=>{Ol();V();_e();hs();fs=class extends lr{static{o(this,"SignJWT")}setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){var n;let i=new hn(Y.encode(JSON.stringify(this._payload)));if(i.setProtectedHeader(this._protectedHeader),Array.isArray((n=this._protectedHeader)===null||n===void 0?void 0:n.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new pe("JWTs MUST NOT use unencoded payload");return i.sign(t,r)}}});var ms,Sm=I(()=>{Pl();_e();hs();ms=class extends lr{static{o(this,"EncryptJWT")}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(t,r){let n=new pn(Y.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(t,r)}}});async function xl(e,t){if(!Q(e))throw new TypeError("JWK must be an object");if(t??(t="sha256"),t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":dr(e.crv,'"crv" (Curve) Parameter'),dr(e.x,'"x" (X Coordinate) Parameter'),dr(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":dr(e.crv,'"crv" (Subtype of Key Pair) Parameter'),dr(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":dr(e.e,'"e" (Exponent) Parameter'),dr(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":dr(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new k('"kty" (Key Type) Parameter missing or unsupported')}let n=Y.encode(JSON.stringify(r));return Z(await qo(t,n))}async function Im(e,t){t??(t="sha256");let r=await xl(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}var dr,Am=I(()=>{Qu();Re();V();_e();$e();dr=o((e,t)=>{if(typeof e!="string"||!e)throw new ni(`${t} missing or invalid`)},"check");o(xl,"calculateJwkThumbprint");o(Im,"calculateJwkThumbprintUri")});async function Rm(e,t){let r={...e,...t?.header};if(!Q(r.jwk))throw new z('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await ar({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||n.type!=="public")throw new z('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}var Pm=I(()=>{di();$e();V();o(Rm,"EmbeddedJWK")});function yS(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new k('Unsupported "alg" value for a JSON Web Key Set')}}function Cl(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(gS)}function gS(e){return Q(e)}function bS(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}async function Om(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let i=await ar({...t,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new rr("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function Nm(e){let t=new gi(e);return async function(r,n){return t.getKey(r,n)}}var gi,Ll=I(()=>{di();V();$e();o(yS,"getKtyFromAlg");o(Cl,"isJWKSLike");o(gS,"isJWKLike");o(bS,"clone");gi=class{static{o(this,"LocalJWKSet")}constructor(t){if(this._cached=new WeakMap,!Cl(t))throw new rr("JSON Web Key Set malformed");this._jwks=bS(t)}async getKey(t,r){let{alg:n,kid:i}={...t,...r?.header},s=yS(n),a=this._jwks.keys.filter(l=>{let d=s===l.kty;if(d&&typeof i=="string"&&(d=i===l.kid),d&&typeof l.alg=="string"&&(d=n===l.alg),d&&typeof l.use=="string"&&(d=l.use==="sig"),d&&Array.isArray(l.key_ops)&&(d=l.key_ops.includes("verify")),d&&n==="EdDSA"&&(d=l.crv==="Ed25519"||l.crv==="Ed448"),d)switch(n){case"ES256":d=l.crv==="P-256";break;case"ES256K":d=l.crv==="secp256k1";break;case"ES384":d=l.crv==="P-384";break;case"ES512":d=l.crv==="P-521";break}return d}),{0:c,length:u}=a;if(u===0)throw new Cr;if(u!==1){let l=new ii,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(let p of a)try{yield await Om(d,p,n)}catch{continue}},l}return Om(this._cached,c,n)}};o(Om,"importWithAlgCache");o(Nm,"createLocalJWKSet")});var _S,xm,Cm=I(()=>{V();_S=o(async(e,t,r)=>{let n,i,s=!1;typeof AbortController=="function"&&(n=new AbortController,i=setTimeout(()=>{s=!0,n.abort()},t));let a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(c=>{throw s?new oi:c});if(i!==void 0&&clearTimeout(i),a.status!==200)throw new me("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new me("Failed to parse the JSON Web Key Set HTTP response as JSON")}},"fetchJwks"),xm=_S});function ES(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}function Lm(e,t){let r=new Dl(e,t);return async function(n,i){return r.getKey(n,i)}}var Dl,Dm=I(()=>{Cm();V();Ll();o(ES,"isCloudflareWorkers");Dl=class extends gi{static{o(this,"RemoteJWKSet")}constructor(t,r){if(super({keys:[]}),this._jwks=void 0,!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.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}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(t,r){(!this._jwks||!this.fresh())&&await this.reload();try{return await super.getKey(t,r)}catch(n){if(n instanceof Cr&&this.coolingDown()===!1)return await this.reload(),super.getKey(t,r);throw n}}async reload(){this._pendingFetch&&ES()&&(this._pendingFetch=void 0),this._pendingFetch||(this._pendingFetch=xm(this._url,this._timeoutDuration,this._options).then(t=>{if(!Cl(t))throw new rr("JSON Web Key Set malformed");this._jwks={keys:t.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(t=>{throw this._pendingFetch=void 0,t})),await this._pendingFetch}};o(Lm,"createRemoteJWKSet")});var ys,Um=I(()=>{Re();_e();V();ls();hs();ys=class extends lr{static{o(this,"UnsecuredJWT")}encode(){let t=Z(JSON.stringify({alg:"none"})),r=Z(JSON.stringify(this._payload));return`${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new pe("Unsecured JWT must be a string");let{0:n,1:i,2:s,length:a}=t.split(".");if(a!==3||s!=="")throw new pe("Invalid Unsecured JWT");let c;try{if(c=JSON.parse(ue.decode(te(n))),c.alg!=="none")throw new Error}catch{throw new pe("Invalid Unsecured JWT")}return{payload:dn(c,te(i),r),header:c}}}});var Ul={};Wi(Ul,{decode:()=>bi,encode:()=>wS});var wS,bi,gs=I(()=>{Re();wS=Z,bi=te});function Mm(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(ue.decode(bi(t)));if(!Q(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var km=I(()=>{gs();_e();$e();o(Mm,"decodeProtectedHeader")});function Hm(e){if(typeof e!="string")throw new pe("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new pe("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new pe("Invalid JWT");if(!t)throw new pe("JWTs must contain a payload");let n;try{n=bi(t)}catch{throw new pe("Failed to parse the base64url encoded payload")}let i;try{i=JSON.parse(ue.decode(n))}catch{throw new pe("Failed to parse the decoded payload as JSON")}if(!Q(i))throw new pe("Invalid JWT Claims Set");return i}var Fm=I(()=>{gs();_e();$e();V();o(Hm,"decodeJwt")});async function qm(e,t){var r;let n,i,s;switch(e){case"HS256":case"HS384":case"HS512":n=parseInt(e.slice(-3),10),i={name:"HMAC",hash:`SHA-${n}`,length:n},s=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return n=parseInt(e.slice(-3),10),nr(new Uint8Array(n>>3));case"A128KW":case"A192KW":case"A256KW":n=parseInt(e.slice(1,4),10),i={name:"AES-KW",length:n},s=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":n=parseInt(e.slice(1,4),10),i={name:"AES-GCM",length:n},s=["encrypt","decrypt"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return U.subtle.generateKey(i,(r=t?.extractable)!==null&&r!==void 0?r:!1,s)}function Ml(e){var t;let r=(t=e?.modulusLength)!==null&&t!==void 0?t:2048;if(typeof r!="number"||r<2048)throw new k("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function $m(e,t){var r,n,i;let s,a;switch(e){case"PS256":case"PS384":case"PS512":s={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ml(t)},a=["sign","verify"];break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ml(t)},a=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ml(t)},a=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":s={name:"ECDSA",namedCurve:"P-256"},a=["sign","verify"];break;case"ES384":s={name:"ECDSA",namedCurve:"P-384"},a=["sign","verify"];break;case"ES512":s={name:"ECDSA",namedCurve:"P-521"},a=["sign","verify"];break;case"EdDSA":a=["sign","verify"];let c=(r=t?.crv)!==null&&r!==void 0?r:"Ed25519";switch(c){case"Ed25519":case"Ed448":s={name:c};break;default:throw new k("Invalid or unsupported crv option provided")}break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{a=["deriveKey","deriveBits"];let u=(n=t?.crv)!==null&&n!==void 0?n:"P-256";switch(u){case"P-256":case"P-384":case"P-521":{s={name:"ECDH",namedCurve:u};break}case"X25519":case"X448":s={name:u};break;default:throw new k("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return U.subtle.generateKey(s,(i=t?.extractable)!==null&&i!==void 0?i:!1,a)}var kl=I(()=>{Ie();V();si();o(qm,"generateSecret");o(Ml,"getModulusLengthOption");o($m,"generateKeyPair")});async function jm(e,t){return $m(e,t)}var Vm=I(()=>{kl();o(jm,"generateKeyPair")});async function Gm(e,t){return qm(e,t)}var Bm=I(()=>{kl();o(Gm,"generateSecret")});var bs={};Wi(bs,{CompactEncrypt:()=>pn,CompactSign:()=>hn,EmbeddedJWK:()=>Rm,EncryptJWT:()=>ms,FlattenedEncrypt:()=>Mt,FlattenedSign:()=>ur,GeneralEncrypt:()=>as,GeneralSign:()=>ps,SignJWT:()=>fs,UnsecuredJWT:()=>ys,base64url:()=>Ul,calculateJwkThumbprint:()=>xl,calculateJwkThumbprintUri:()=>Im,compactDecrypt:()=>ns,compactVerify:()=>us,createLocalJWKSet:()=>Nm,createRemoteJWKSet:()=>Lm,decodeJwt:()=>Hm,decodeProtectedHeader:()=>Mm,errors:()=>Xu,exportJWK:()=>is,exportPKCS8:()=>um,exportSPKI:()=>cm,flattenedDecrypt:()=>an,flattenedVerify:()=>cn,generalDecrypt:()=>im,generalVerify:()=>hm,generateKeyPair:()=>jm,generateSecret:()=>Gm,importJWK:()=>ar,importPKCS8:()=>Xf,importSPKI:()=>Yf,importX509:()=>Zf,jwtDecrypt:()=>bm,jwtVerify:()=>ym});var _s=I(()=>{bl();rs();om();lm();Il();cs();fm();gm();_m();Pl();ss();Ol();ds();vm();Tm();Sm();Am();Pm();Ll();Dm();Um();_l();di();km();Fm();V();Vm();Bm();gs()});var ws=g(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});Es.fetchRetry=void 0;var vS=D();async function TS(e,t,r){for(let n=0;n<=e.retries;n++){let i=fetch(t,r);if(n===e.retries)return i;let s=await i;if(s.status<500&&s.status!==429)return s;e?.logger?.error("Request failed, retrying",{method:typeof t=="string"?"GET":t.method,url:typeof t=="string"?t:t.url,status:s.status}),await new Promise(a=>setTimeout(a,e.retryDelayMs*Math.pow(2,n)))}throw new vS.ConfigurationError("An unknown error occurred, ensure retries is not negative")}o(TS,"fetchRetry");Es.fetchRetry=TS});var fn=g(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.GcpServiceAccount=et.fetchToken=et.exchangeGgpJwtForIdToken=et.exchangeFirebaseJwtForIdToken=et.getTokenFromGcpServiceAccount=void 0;var Km=(_s(),Qi(bs)),SS=D(),IS=ws();async function AS({serviceAccount:e,audience:t,expirationTime:r="1h",payload:n={}}){let{clientEmail:i,privateKeyId:s,privateKey:a}=e;return await new Km.SignJWT(n).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(i).setSubject(i).setAudience(t).setIssuedAt().setExpirationTime(r).sign(a)}o(AS,"getTokenFromGcpServiceAccount");et.getTokenFromGcpServiceAccount=AS;async function RS(e,t,r){return Fl(e,{token:t,returnSecureToken:!0},r)}o(RS,"exchangeFirebaseJwtForIdToken");et.exchangeFirebaseJwtForIdToken=RS;async function PS(e,t,r){return Fl(e,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:t},r)}o(PS,"exchangeGgpJwtForIdToken");et.exchangeGgpJwtForIdToken=PS;async function Fl(e,t,r){let n=await(0,IS.fetchRetry)(r,e,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(t)});if(n.status!==200){let s;try{let a=await n.text(),c=JSON.parse(a);s={cause:c.error??c}}catch{}throw new SS.RuntimeError({message:"Could not get token from Google Identity",extensionMembers:s})}return await n.json()}o(Fl,"fetchToken");et.fetchToken=Fl;var Hl=class e{static{o(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:t,privateKey:r}){this.#t=t,this.#e=r}static async init(t){let r=JSON.parse(t),n=await(0,Km.importPKCS8)(r.private_key.trim(),"RS256");return new e({serviceAccount:r,privateKey:n})}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}};et.GcpServiceAccount=Hl});var Ts=g(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.GoogleLogTransport=kt.ZuploToGCPMap=kt.GoogleCloudLoggingPlugin=void 0;var OS=Se(),ql=ee(),$l=fn(),NS=Dt(),Jm=gt(),jl=class extends NS.LogPlugin{static{o(this,"GoogleCloudLoggingPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new vs(this.options)}};kt.GoogleCloudLoggingPlugin=jl;var xS="https://logging.googleapis.com/v2/entries:write?alt=json";kt.ZuploToGCPMap={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"};var vs=class{static{o(this,"GoogleLogTransport")}constructor(t){this.#r=t.logName,this.#e=t.serviceAccountJson,this.#i=ql.Environment.instance.loggingEnvironmentType,this.#o=ql.Environment.instance.loggingEnvironmentStage,this.#n=ql.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;async log(t,r){if(t.messages.length===0)return;let n={allMessages:(0,Jm.makeErrorsSerializable)(t.messages)};this.#t||(this.#t=await $l.GcpServiceAccount.init(this.#e));let i=this.#t.projectId??"zuplo-production",s={logName:this.#r,resource:{type:"global"},severity:kt.ZuploToGCPMap[t.level],timestamp:t.timestamp,trace:`projects/${i}/traces/${t.requestId}`,labels:{requestId:t.requestId,buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner,environment:this.#n,environmentType:this.#i,environmentStage:this.#o}};t.rayId&&(s.labels.rayId=t.rayId);let a=(0,Jm.extractBestMessage)(n.allMessages);s.jsonPayload={...n,message:a},this.batcher.enqueue(s),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async t=>{if(t.length===0)return;this.#t||(this.#t=await $l.GcpServiceAccount.init(this.#e));let r=await(0,$l.getTokenFromGcpServiceAccount)({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),n=await fetch(xS,{method:"POST",body:JSON.stringify({entries:t}),headers:{Authorization:`Bearer ${r}`,"content-type":"application/json;charset=UTF-8"}});n.ok||console.error(n.status,n.statusText,await n.text())};batcher=new OS.BatchDispatch("google-log-transport",1,this.dispatchFunction)};kt.GoogleLogTransport=vs});var Vl=g(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.gcpLogFormat=mn.GCP_LOG_FORMAT=void 0;var zm=gt(),CS=Ts();mn.GCP_LOG_FORMAT="gcp";function LS(e){let t={allMessages:(0,zm.makeErrorsSerializable)(e.messages)},r="zuplo-production",n=(0,zm.extractBestMessage)(t.allMessages),i={logName:`projects/${r}/logs/runtime-user`,message:n,severity:CS.ZuploToGCPMap[e.level],timestamp:e.timestamp,"logging.googleapis.com/labels":{buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner},"logging.googleapis.com/trace":`projects/${r}/traces/${e.requestId}`,allMessages:t.allMessages};return e.rayId&&(i["logging.googleapis.com/labels"].rayId=e.rayId),i}o(LS,"gcpLogFormat");mn.gcpLogFormat=LS});var Qm=g(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.ConsoleTransport=void 0;var Wm=Vl(),Gl=class{static{o(this,"ConsoleTransport")}constructor(t,r){this.#e=t??console,this.#t=r}#e;#t;async log(t){if(this.#t===Wm.GCP_LOG_FORMAT){if(t.messages.length===0)return;this.#e[t.level].apply(null,[(0,Wm.gcpLogFormat)(t)])}else this.#e[t.level].apply(null,[...t.messages,{logOwner:t.logOwner,logSource:t.logSource,level:t.level,timestamp:t.timestamp,loggingId:t.loggingId,rayId:t.rayId,requestId:t.requestId,buildId:t.buildId}])}};Ss.ConsoleTransport=Gl});var Ql=g(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.DataDogTransport=yn.DataDogLoggingPlugin=void 0;var DS=Se(),Bl=ee(),US=Dt(),Ym=gt(),Wl=class extends US.LogPlugin{static{o(this,"DataDogLoggingPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new Is(this.options)}};yn.DataDogLoggingPlugin=Wl;var Kl="__ddtags",Jl="__ddattr",zl=o(e=>e.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),MS=o(e=>{let t=Object.keys(e),r=[];return t.forEach(n=>{let i=e[n];i==null?r.push(zl(n)):r.push(`${zl(n)}:${zl(i.toString())}`)}),r.join(",")},"formatTags"),Is=class{static{o(this,"DataDogTransport")}constructor(t){this.#e=t.apiKey,this.#t=t.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#n=Bl.Environment.instance.loggingEnvironmentType,this.#i=Bl.Environment.instance.loggingEnvironmentStage,this.#r=Bl.Environment.instance.deploymentName}#e;#t;#r;#n;#i;async log(t,r){let n={},i=r.custom[Kl];i&&typeof i=="object"&&Object.assign(n,i);let s=[...t.messages],a=t.messages.findIndex(h=>h[Kl]!==void 0);a>-1&&(Object.assign(n,s[a][Kl]),s.splice(a,1));let c={},u=r.custom[Jl];u&&typeof u=="object"&&Object.assign(c,u);let l=t.messages.findIndex(h=>h[Jl]!==void 0);l>-1&&(Object.assign(c,s[l][Jl]),s.splice(l,1));let d=(0,Ym.makeErrorsSerializable)(s),y={message:{...{...t,activityId:t.requestId,trace:t.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(r.originalRequest.url).hostname,msg:(0,Ym.extractBestMessage)(d),service:t.loggingId,ddtags:MS(n),environment:this.#r,environment_type:this.#n,environment_stage:this.#i};Object.assign(y,c),this.batcher.enqueue(y),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async t=>{t.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...t]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new DS.BatchDispatch("data-dog-transport",10,this.dispatchFunction)};yn.DataDogTransport=Is});var Xm=g(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.ProcessTransport=void 0;var Zm=Vl(),Yl=class{static{o(this,"ProcessTransport")}constructor(t,r){this.#e=t,this.#t=r}#e;#t;async log(t){if(this.#t===Zm.GCP_LOG_FORMAT){if(t.messages.length===0)return;this.#e[t.level].apply(null,[(0,Zm.gcpLogFormat)(t)])}else this.#e[t.level].apply(null,[...t.messages,{logOwner:t.logOwner,logSource:t.logSource,timestamp:t.timestamp,loggingId:t.loggingId,rayId:t.rayId,requestId:t.requestId,buildId:t.buildId,vectorClock:t.vectorClock}])}};As.ProcessTransport=Yl});var ty=g(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});Ps.RemoteLogTransport=void 0;var kS=Se(),ey=ee(),HS=gt(),FS=o(({url:e,remoteLogToken:t,loggingId:r,sendOnlyErrors:n})=>async i=>{let s;n===!0?s=i.filter(a=>a.level==="error"):s=i,s.length!==0&&fetch(`${e}/publish/${r}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:(0,HS.makeErrorsSerializable)(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":ey.Environment.instance.systemUserAgent,"zp-dn":ey.Environment.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),Rs,Zl=class{static{o(this,"RemoteLogTransport")}constructor(t){Rs||(Rs=new kS.BatchDispatch("remote-log-transport",1,FS(t)))}async log(t,r){Rs.enqueue(t),r.waitUntil(Rs.waitUntilFlushed())}};Ps.RemoteLogTransport=Zl});var ry=g(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.unifiedFormatter=Ur.SeverityNumberOpenTelemetryMap=void 0;Ur.SeverityNumberOpenTelemetryMap={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21};var qS=o((e,t)=>r=>{let n={};return n.deploymentName=e,n.labels={requestId:r.requestId,source:r.logSource,loggingId:r.loggingId,logOwner:r.logOwner},n.rayId=r.rayId??"",n.runtime={buildId:t.BUILD_ID,buildTimestamp:t.TIMESTAMP,gitSHA:t.GIT_SHA,version:t.ZUPLO_VERSION},n.atomicCounter=r.vectorClock,{timestamp:r.timestamp,observerdTimestamp:r.timestamp,traceId:r.requestId,severityText:r.level,severityNumber:Ur.SeverityNumberOpenTelemetryMap[r.level],body:r.messages,attributes:n}},"unifiedFormatter");Ur.unifiedFormatter=qS});var iy=g(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.UnifiedLogTransport=void 0;var $S=Se(),ny=ee(),jS=ry(),VS=o(({url:e,remoteLogToken:t,deploymentName:r,build:n})=>async i=>{if(i.length===0)return;let s=(0,jS.unifiedFormatter)(r,n);fetch(`${e}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:i.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":ny.Environment.instance.systemUserAgent,"zp-dn":ny.Environment.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),Os,Xl=class{static{o(this,"UnifiedLogTransport")}constructor(t){Os||(Os=new $S.BatchDispatch("unified-log-transport",1,VS(t)))}async log(t,r){Os.enqueue(t),r.waitUntil(Os.waitUntilFlushed())}};Ns.UnifiedLogTransport=Xl});var dy=g(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.LogInitializer=void 0;var GS=Sr(),BS=xt(),oy=Fu(),sy=ee(),ay=uf(),KS=Dt(),JS=lf(),cy=df(),uy=Qm(),zS=Ql(),WS=Ts(),ly=Xm(),QS=ty(),YS=iy(),ed=(0,GS.debug)("zuplo:logging"),td=class{static{o(this,"LogInitializer")}serviceProvider;systemCoreLogger;userCoreLogger;constructor(t){this.serviceProvider=t,this.systemCoreLogger=this.setupSystemCoreLogger(sy.Environment.instance),this.userCoreLogger=this.setupUserCoreLogger(sy.Environment.instance)}setupSystemCoreLogger(t){let{build:r}=t;ed("Gateway.setupSystemCoreLogger");let n=[],i=this.serviceProvider.getService(oy.SYSTEM_LOGGER);return i?n.push(new ly.ProcessTransport(i.logger,t.logFormat)):t.isDeno&&n.push(new uy.ConsoleTransport(console,t.logFormat)),t.isCloudflare&&t.deploymentName&&t.remoteLogToken&&n.push(new YS.UnifiedLogTransport({url:t.remoteLogURL,deploymentName:t.deploymentName,remoteLogToken:t.remoteLogToken,build:t.build})),new ay.CoreLogger(t.systemLogLevel,"system",t.loggingId,r.BUILD_ID,n)}setupUserCoreLogger(t){ed("Gateway.setupUserCoreLogger");let r=[],{runtime:n,build:i}=t,s=this.serviceProvider.getService(oy.SYSTEM_LOGGER);if(s&&s.captureUserLogs===!0?r.push(new ly.ProcessTransport(s.logger,t.logFormat)):t.isDeno&&r.push(new uy.ConsoleTransport(console,t.logFormat)),t.remoteLogToken&&t.loggingId&&r.push(new QS.RemoteLogTransport({loggingId:t.loggingId,url:t.remoteLogURL,remoteLogToken:t.remoteLogToken,sendOnlyErrors:t.isCloudflare})),n.GCP_USER_LOG_NAME&&n.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new WS.GoogleLogTransport({serviceAccountJson:n.GCP_USER_LOG_SVC_ACCT_JSON,logName:n.GCP_USER_LOG_NAME})),n.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let a=n.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new zS.DataDogTransport({apiKey:n.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:a}))}return BS.plugins.forEach(a=>{a instanceof KS.LogPlugin&&r.push(a.getTransport())}),new ay.CoreLogger(t.userLogLevel,"user",t.loggingId,i.BUILD_ID,r)}createRequestLoggers(t,r,n,i,s){ed("Gateway.createRequestLoggers");let a=new JS.LoggingContext(n,i,s),c=new cy.RequestLogger(t,r,this.systemCoreLogger,a);return{userRequestLogger:new cy.RequestLogger(t,r,this.userCoreLogger,a),systemRequestLogger:c}}};xs.LogInitializer=td});var nd=g(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.UserRouteConfiguration=void 0;var rd=class{static{o(this,"UserRouteConfiguration")}constructor(t){this.path=t.path,this.methods=t.methods,this.label=t.label,this.key=t.key,this.handler=t.handler,this.corsPolicy=t.corsPolicy,this.custom=t.custom,this.version=t.version,this.policies=t.policies,this.excludeFromOpenApi=t.excludeFromOpenApi,this.pathPattern=t.pathPattern,t.raw?(this.#e=t.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=t.operationId,this.summary=t.summary,this.tags=t.tags,this.parameters=t.parameters,this.responses=t.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};Cs.UserRouteConfiguration=rd});var od=g(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.Router=wt.RouterError=wt.LookupResult=wt.RouterEntry=void 0;var py=D(),ZS=mt(),XS=nd(),Ls=class{static{o(this,"RouterEntry")}constructor(t,r,n,i){this.fullPath=t,this.urlPattern=r,this.config=n,this.executableHandler=i}fullPath;urlPattern;config;executableHandler};wt.RouterEntry=Ls;var _i=class{static{o(this,"LookupResult")}constructor(t,r,n){this.routeConfiguration=t,this.params=n??{},this.executableHandler=r}executableHandler;routeConfiguration;params};wt.LookupResult=_i;var Ds=class extends Error{static{o(this,"RouterError")}constructor(t,r){super(t,r)}};wt.RouterError=Ds;var id=class{static{o(this,"Router")}constructor(t){this.routeEntries=[],this.versions=t}versions;routeEntries;addRoute(t,r){if(!(t instanceof XS.UserRouteConfiguration||t instanceof ZS.SystemRouteConfiguration))throw new py.SystemError("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let n=this.versions.find(s=>s.name===t.version)?.pathPrefix,i;"pathPattern"in t&&t.pathPattern?i=`${n??""}${t.pathPattern}`:i=`${n??""}${t.path}`;try{let s=new URLPattern({pathname:i}),a=new Ls(i,s,t,r);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Ds(`addRoute-error: Invalid path '${i}'. '${s.message}'`,{cause:s})}}lookup(t,r){if(typeof t>"u")throw new py.ConfigurationError(`Invalid request - Method was undefined. Path: '${r}'`);let n=this.routeEntries.filter(i=>i.config.methods.includes(t));if(n.length!==0)for(let i=0;i<n.length;i++){let s=n[i],c=s.urlPattern.exec({pathname:r});if(c!==null)return new _i(s.config,s.executableHandler,c.pathname.groups)}}lookupByPathOnly(t){let r=[];for(let n=0;n<this.routeEntries.length;n++){let i=this.routeEntries[n],a=i.urlPattern.exec({pathname:t});if(a!==null){let c=new _i(i.config,i.executableHandler,a.pathname.groups);r.push(c)}}return r}};wt.Router=id});var Mr=g(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.Gateway=void 0;var eI=Sr(),hy=Uh(),fy=Vh(),tI=Gh(),my=Bh(),yy=Wh(),Ht=Zn(),Us=Ir(),gy=cf(),Tt=D(),sd=xt(),rI=dy(),nI=Wt(),iI=le(),oI=Mu(),sI=Rr(),aI=ri(),cI=Je(),uI=od(),ad=mt(),by=nd(),lI=Ke(),dI=Ro(),_y=ee(),Ey=xr(),pI=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],vt=(0,eI.debug)("zuplo:runtime"),hI=o(e=>{let t=e.findIndex(r=>r.name===ad.systemNoVersion.name);return t>-1?[...e.splice(t),ad.systemNoVersion]:[...e,ad.systemNoVersion]},"setupSystemNoVersion"),cd=class e{static{o(this,"Gateway")}routeData;runtimeSettings;schemaValidator;static#e;constructor(t,r,n,i){this.routeData=t,this.runtimeSettings=r,this.schemaValidator=i,vt("Gateway.constructor"),this.#r=this.setupRoutes(),this.#i=this.setupErrorHandler(),this.#t=new rI.LogInitializer(n)}static async initialize(t,r,n,i,s){if(vt("Gateway.initialize"),!e.#e){await(0,sd.initializeRuntime)(s);let a={...t,corsPolicies:(0,dI.parseCorsPolicies)(t.corsPolicies)},c=new e(a,r,n,i);e.#e=c}return e.#e}static purgeGatewayCache(){vt("Gateway.purgeGatewayCache"),e.#e=void 0}static get instance(){if(!e.#e)throw new Tt.SystemError("Gateway cannot be used before it is initialized");return e.#e}instanceId=crypto.randomUUID();#t;#r;#n=[aI.policyProcessor,oI.corsProcessor,sI.metricsProcessor];#i;setupRoutes=()=>{vt("Gateway.setupRoutes");let t=this.routeData,r=hI(t.versions),n=new uI.Router(r);if(t.routes.length===0)return(0,hy.registerBuildRoute)(n,this),(0,yy.registerPingRoute)(n,this),(0,fy.registerCorsRoute)(n,this),(0,tI.registerNoRoutes)(n,this),n;let{enabled:i}=this.runtimeSettings.developerPortal;return i&&((0,gy.registerDevPortalLegacyRedirectRoute)(n,this),(0,gy.registerDevPortalV3Route)(n,this)),(0,hy.registerBuildRoute)(n,this),(0,yy.registerPingRoute)(n,this),(0,fy.registerCorsRoute)(n,this),t.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new Tt.ConfigurationError(`Invalid state - No handler on route for path '${s.path}'`);let c=a,u=new nI.Pipeline(this.#n,c,this),l=new by.UserRouteConfiguration(s);n.addRoute(l,u.execute)}),(0,my.registerNotMatchedHandler)(n,this),n};setupErrorHandler=()=>{let t;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(t=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof t!="function")throw new Tt.ConfigurationError("Invalid state - Module and export set for 'errorHandler' is not a function")}else t=o((r,n,i)=>this.#o(r,n,i),"errorHandler");return t};errorHandler(t,r,n){try{return this.#i(t,r,n)}catch(i){return vt("An error occurred in the user's errorHandler",i),this.#o(t,r,i)}}#o(t,r,n){vt("Gateway.internalErrorResponse");let i={};if(_y.Environment.instance.isDeno){if(n instanceof Tt.RuntimeError&&n.extensionMembers)i=n.extensionMembers;else if(n.cause){let s=(0,Ey.serializeError)(n.cause);"stack"in s&&(s.stack=(0,Ey.cleanStack)(s.stack)),i={cause:s}}}return iI.HttpProblems.internalServerError(t,r,{detail:n.message,...i})}#s(t){let r=new Headers(t.headers);return Ht.DISPATCH_HEADERS_TO_REMOVE.forEach(n=>{r.delete(n)}),_y.Environment.instance.isDeno&&Ht.INTERNAL_HEADERS_TO_REMOVE.forEach(n=>{r.delete(n)}),new Request(t,{headers:r})}async handleRequest(t,r){let n=t.headers.get(Ht.REQUEST_ID_HEADER)??t.headers.get(Ht.LEGACY_REQUEST_ID_HEADER),i=t.headers.get(Ht.RAY_ID_HEADER);if(!n){n=crypto.randomUUID();let T=new Headers(t.headers);T.set(Ht.REQUEST_ID_HEADER,n),t=new Request(t,{headers:T})}if(["GET","HEAD"].includes(t.method)&&t.body){let T=new Headers(t.headers);T.set(Ht.BODY_REMOVED_HEADER,"true"),t=new Request(t,{headers:T,body:null})}let s={},{userRequestLogger:a,systemRequestLogger:c}=this.#t.createRequestLoggers(n,i,r,s,t),u=new URL(t.url),l=u.pathname,d=this.#r.lookup(t.method,l);if(!d)throw new Tt.SystemError(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Us.HeaderIncomingRequestProperties(t.headers),y=this.#s(t),h=new cI.ZuploRequest(y,{params:d.params}),m=new Us.SystemZuploContext({logger:a,route:d.routeConfiguration,requestId:n,fetchEvent:r,custom:s,incomingRequestProperties:p}),v=Us.ZuploContextExtensions.initialize(m,h);if(d.routeConfiguration===my.notFoundRouteConfiguration&&sd.runtimeExtensions.value?.notFoundHandler!==void 0){let T=this.#r.lookupByPathOnly(l);v.pathOnlyMatches=T.map(S=>S.routeConfiguration).filter(S=>S instanceof by.UserRouteConfiguration)}try{if(lI.SystemLogMap.addLogger(m,c),!u.pathname.startsWith("/__zuplo")){let j=await(0,sd.invokeOnRequestExtensions)(h,m);if(j instanceof Response)return j;{let L=Us.ZuploContextExtensions.getContextExtensions(m);h=j,L.latestRequest=h}}[...pI,...this.runtimeSettings.developerPortal.enabled?[this.runtimeSettings.developerPortal.sitePathname]:[]].filter(j=>new RegExp(j).test(u.pathname)).length===0&&a.debug(`Request received '${u.pathname}'`,{method:t.method,url:u.pathname,hostname:u.hostname,route:d.routeConfiguration.path});let S=d.executableHandler;fI(S,d,t),vt("Gateway.handleRequest - call user handler");let O=await S(h,m);if(vt("Gateway.handleRequest - user handler"),!(O instanceof Response))throw new Tt.RuntimeError(`Invalid Response type from the request handler: ${typeof O}`);if(O.bodyUsed)throw new Tt.RuntimeError("The response object has already been used. Return a new response instead.");if(O.headers.get(Ht.REQUEST_ID_HEADER)===null&&!O.webSocket){let j=new Headers(O.headers);return j.set(Ht.REQUEST_ID_HEADER,n),new Response(O.body,{status:O.status,statusText:O.statusText,headers:j,cf:O.cf})}else return O}catch(T){return vt("Gateway - error executing handler",T),T instanceof Tt.RuntimeError?(a.error(T),c.warn(T)):c.error(T),await this.#o(h,m,T)}}};Ms.Gateway=cd;function fI(e,t,r){if(vt("Gateway.checkHandler"),!e)throw typeof t.routeConfiguration>"u"?new Tt.ConfigurationError(`Invalid state - no routeConfiguration for '${r.method}:${r.url}`):new Tt.ConfigurationError(`Invalid state. No handler for request '${r.method}':'${t.routeConfiguration.path}'`)}o(fI,"checkHandler")});var wy=g(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.invokeInboundPolicy=void 0;var mI=D(),yI=Mr(),gI=ri(),bI=o(async(e,t,r)=>{let n=yI.Gateway.instance.routeData.policies,i=(0,gI.getInboundPolicyHandlerAndOptions)([e],n);if(i.length===0)throw new mI.RuntimeError(`Invalid 'invokeInboundPolicy call' - no policy '${e}' found.`);let s=i[0];return s.handler(t,r,s.options,e)},"invokeInboundPolicy");ks.invokeInboundPolicy=bI});var Ir=g(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.SystemZuploContext=tt.ZuploContextExtensions=tt.ResponseSentEvent=tt.ResponseSendingEvent=tt.HeaderIncomingRequestProperties=void 0;var we=Zn(),_I=D(),EI=wy(),ud=class{static{o(this,"HeaderIncomingRequestProperties")}#e;constructor(t){this.#e=t}get asn(){try{let t=this.#e.get(we.ZP_ASN_HEADER);if(typeof t=="string")return parseInt(t)}catch{}}get asOrganization(){return this.#e.get(we.ZP_AS_ORG_HEADER)??void 0}get city(){return this.#e.get(we.CF_IP_CITY_HEADER)??this.#e.get(we.ZP_IP_CITY_HEADER)??void 0}get continent(){return this.#e.get(we.CF_IP_CONTINENT_HEADER)??this.#e.get(we.ZP_IP_CONTINENT_HEADER)??void 0}get country(){return this.#e.get(we.CF_IP_COUNTRY_HEADER)??this.#e.get(we.ZP_IP_COUNTRY_HEADER)??void 0}get latitude(){return this.#e.get(we.CF_IP_LATITUDE_HEADER)??this.#e.get(we.ZP_IP_LATITUDE_HEADER)??void 0}get longitude(){return this.#e.get(we.CF_IP_LONGITUDE_HEADER)??this.#e.get(we.ZP_IP_LONGITUDE_HEADER)??void 0}get colo(){return this.#e.get(we.ZP_COLO_HEADER)??void 0}get postalCode(){return this.#e.get(we.ZP_POSTAL_CODE_HEADER)??void 0}get metroCode(){return this.#e.get(we.ZP_METRO_CODE_HEADER)??void 0}get region(){return this.#e.get(we.ZP_REGION_HEADER)??void 0}get regionCode(){return this.#e.get(we.ZP_REGION_CODE_HEADER)??void 0}get timezone(){return this.#e.get(we.ZP_TIMEZONE_HEADER)??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}}};tt.HeaderIncomingRequestProperties=ud;var ld=class extends Event{static{o(this,"ResponseSendingEvent")}constructor(t,r){super("responseSending"),this.request=t,this.mutableResponse=r}request;mutableResponse};tt.ResponseSendingEvent=ld;var dd=class extends Event{static{o(this,"ResponseSentEvent")}constructor(t,r){super("responseSent"),this.request=t,this.response=r}request;response};tt.ResponseSentEvent=dd;var Ei=class e{static{o(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(t,r){if(!e.#e.has(t)){let n=new e(r);return e.#e.set(t,n),n}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${t.requestId}'`)}static getContextExtensions(t){let r=e.#e.get(t);if(!r)throw new _I.RuntimeError(`Invalid state, could not get ZuploContext extensions for context with requestId '${t.requestId}'`);return r}latestRequest;pathOnlyMatches;#t;#r;constructor(t){this.latestRequest=t,this.#t=[],this.#r=[]}addResponseSendingHook(t){this.#r.push(t)}addResponseSendingFinalHook(t){this.#t.push(t)}onResponseSendingFinal=async(t,r,n)=>{for(let i of this.#t)await i(t,r,n)};onResponseSending=async(t,r,n)=>{let i=t;for(let s of this.#r)i=await s(t,r,n);return i}};tt.ZuploContextExtensions=Ei;var pd=class extends EventTarget{static{o(this,"SystemZuploContext")}constructor({logger:t,route:r,requestId:n,fetchEvent:i,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(t),this.route=r,this.requestId=n,this.custom=s,this.incomingRequestProperties=a,this.#e=i,this.invokeInboundPolicy=(c,u)=>(0,EI.invokeInboundPolicy)(c,u,this),this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingHook=c=>{Ei.getContextExtensions(this).addResponseSendingHook(c)},this.addResponseSendingFinalHook=c=>{Ei.getContextExtensions(this).addResponseSendingFinalHook(c)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(t,r,n){let i=o(s=>{try{typeof r=="function"?r(s):r.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${t}. See following logs for details.`),a}},"wrapped");super.addEventListener(t,i,n)}};tt.SystemZuploContext=pd});var vy=g(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.ContextData=void 0;var hd=class e{static{o(this,"ContextData")}static#e;#t;constructor(t){this.#t=t}set(t,r){e.set(t,this.#t,r)}get(t){return e.get(t,this.#t)}static set(t,r,n){e.#e||(e.#e=new WeakMap);let i=e.#e.get(t);i||(i=new Map),i.set(r,n),e.#e.set(t,i)}static get(t,r){return e.#e||(e.#e=new WeakMap),e.#e.get(t)?.get(r)}};Hs.ContextData=hd});var fd=g(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.environment=pr.isZuploReadableEnvVariableName=pr.isRestrictedEnvVariableName=void 0;var wI=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Ty(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!wI.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}o(Ty,"isRestrictedEnvVariableName");pr.isRestrictedEnvVariableName=Ty;function Sy(e){return!!e.startsWith("ZUPLO_")}o(Sy,"isZuploReadableEnvVariableName");pr.isZuploReadableEnvVariableName=Sy;var vI=new Proxy({},{get(e,t){if(Ty(String(t))&&!Sy(String(t)))return;let r=globalThis,n;return r.process?n=r.process.env[t]:n=r[t],n}});pr.environment=vI});var md=g(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.externalServiceHandler=gn.externalServiceTunnelConfig=void 0;var TI=Sr(),kr=D(),SI=yd(),wi=ee(),ct=(0,TI.debug)("zuplo:runtime:external-service");function Ay(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=wi.Environment.instance.runtime;if(t&&t!=="undefined")try{let r=atob(t);e=JSON.parse(r)}catch{}return e}o(Ay,"getServiceAuth");async function II(e){let t=Ay();if(!t)throw ct("There is no external service auth configured for this zup."),new kr.RuntimeError("There are no external services configured for this zup.");if(typeof e!="string")throw ct("Cannot call external service with Request object"),new kr.RuntimeError("Currently, we only support fetch(<some_string>, ...).");let n=new URL(e).hostname,i={};i["CF-Access-Client-Id"]=t.clientId,i["CF-Access-Client-Secret"]=t.clientSecret;let s;if(t.customServiceMapping&&t.customServiceMapping[n])s=`https://${t.customServiceMapping[n]}`;else if(wi.Environment.instance.useSha256ServiceRouting){ct("Using sha256 service routing");let a=wi.Environment.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)s=`https://${await Ry(n,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ct("Cannot use sha256 service routing, missing build variables"),new kr.RuntimeError("Failed to generate fully qualified tunnel url.")}else s=`https://${n}.zuptunnel.com`;return{serviceBaseUrl:s,tunnelHeaders:i}}o(II,"externalServiceTunnelConfig");gn.externalServiceTunnelConfig=II;async function AI(e,t){let r=Ay();if(r)if(ct(`Using external service auth. ClientId: ${r.clientId})`),typeof e=="string"){let n=new URL(e),i=n.hostname,s=t??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",r.clientId),a.set("CF-Access-Client-Secret",r.clientSecret),s.headers=a;let c;if(r.customServiceMapping&&r.customServiceMapping[i])c=`https://${r.customServiceMapping[i]}`;else if(wi.Environment.instance.useSha256ServiceRouting){ct("Using sha256 service routing");let d=wi.Environment.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)c=`https://${await Ry(i,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ct("Cannot use sha256 service routing, missing build variables"),new kr.RuntimeError("Failed to generate fully qualified tunnel url.")}else c=`https://${i}.zuptunnel.com`;let u=new URL(`${c}${n.pathname}${n.search}`);ct(`Calling external service: ${u.toString()}`);let l=await(0,SI.originalFetch)(u.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:r.clientId,tunnelHost:c}),new kr.RuntimeError("Could not connect to secure tunnel.");return l}else throw ct("Cannot call external service with Request object"),new kr.RuntimeError("Currently, we only support fetch(<some_string>, ...).");else throw ct("There is no external service auth configured for this zup."),new kr.RuntimeError("There are no external services configured for this zup.")}o(AI,"externalServiceHandler");gn.externalServiceHandler=AI;async function Ry(e,t,r,n){let i=e.toLowerCase(),s=t.toLowerCase(),a=r.toLowerCase(),c=RI(n);ct(`Hashing service name: ${s}-${i}.${s}-${a}-${c}`);let u=await Iy(`${s}-${i}`),l=await Iy(`${s}-${a}-${c}`);return`${u}.${l}`}o(Ry,"hashServiceName");async function Iy(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}o(Iy,"hashSegment");function RI(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}o(RI,"sanitizeEnvironmentType")});var yd=g(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.originalFetch=void 0;var PI=md(),Py=new Map;Py.set("service:",PI.externalServiceHandler);bn.originalFetch=globalThis.fetch;globalThis.fetch=function(e,t){let r=OI(t);if(typeof e=="string"){let n=new URL(e),i=Py.get(n.protocol);return i?i(e,r):(0,bn.originalFetch)(e,r)}else return(0,bn.originalFetch)(e,r)};var OI=o(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let r=e;return r.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit")});var xy=g(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.Handler=_n.purgeGatewayCache=void 0;var NI=D(),Ny=Mr(),Oy=ee(),xI=o(()=>{Ny.Gateway.purgeGatewayCache()},"purgeGatewayCache");_n.purgeGatewayCache=xI;var gd=class{static{o(this,"Handler")}routeData;buildEnvironment;runtimeEnvironment;runtimeSettings;serviceProvider;schemaValidations;runtimeInit;constructor(t,r,n,i,s,a,c){this.routeData=t,this.buildEnvironment=r,this.runtimeEnvironment=n,this.runtimeSettings=i,this.serviceProvider=s,this.schemaValidations=a,this.runtimeInit=c}requestHandler=async(t,r)=>{Oy.Environment.initialize(this.buildEnvironment,this.runtimeEnvironment);let n;try{n=await Ny.Gateway.initialize(this.routeData,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(i){console.error("Error initializing gateway.",i);let s="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";i instanceof NI.ConfigurationError&&(s=i.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:s,instance:t.url,trace:{timestamp:Date.now(),rayId:t.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:Oy.Environment.instance.isDeno?i.message:void 0};return new Response(JSON.stringify(a,null,2),{status:500,headers:{"content-type":"application/json"}})}return n.handleRequest(t,r)}};_n.Handler=gd});var Uy=g(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.pathToRegexp=Ne.tokensToRegexp=Ne.regexpToFunction=Ne.match=Ne.tokensToFunction=Ne.compile=Ne.parse=void 0;function CI(e){for(var t=[],r=0;r<e.length;){var n=e[r];if(n==="*"||n==="+"||n==="?"){t.push({type:"MODIFIER",index:r,value:e[r++]});continue}if(n==="\\"){t.push({type:"ESCAPED_CHAR",index:r++,value:e[r++]});continue}if(n==="{"){t.push({type:"OPEN",index:r,value:e[r++]});continue}if(n==="}"){t.push({type:"CLOSE",index:r,value:e[r++]});continue}if(n===":"){for(var i="",s=r+1;s<e.length;){var a=e.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){i+=e[s++];continue}break}if(!i)throw new TypeError("Missing parameter name at ".concat(r));t.push({type:"NAME",index:r,value:i}),r=s;continue}if(n==="("){var c=1,u="",s=r+1;if(e[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<e.length;){if(e[s]==="\\"){u+=e[s++]+e[s++];continue}if(e[s]===")"){if(c--,c===0){s++;break}}else if(e[s]==="("&&(c++,e[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));u+=e[s++]}if(c)throw new TypeError("Unbalanced pattern at ".concat(r));if(!u)throw new TypeError("Missing pattern at ".concat(r));t.push({type:"PATTERN",index:r,value:u}),r=s;continue}t.push({type:"CHAR",index:r,value:e[r++]})}return t.push({type:"END",index:r,value:""}),t}o(CI,"lexer");function bd(e,t){t===void 0&&(t={});for(var r=CI(e),n=t.prefixes,i=n===void 0?"./":n,s="[^".concat(En(t.delimiter||"/#?"),"]+?"),a=[],c=0,u=0,l="",d=o(function(ie){if(u<r.length&&r[u].type===ie)return r[u++].value},"tryConsume"),p=o(function(ie){var ge=d(ie);if(ge!==void 0)return ge;var Be=r[u],E=Be.type,H=Be.index;throw new TypeError("Unexpected ".concat(E," at ").concat(H,", expected ").concat(ie))},"mustConsume"),y=o(function(){for(var ie="",ge;ge=d("CHAR")||d("ESCAPED_CHAR");)ie+=ge;return ie},"consumeText");u<r.length;){var h=d("CHAR"),m=d("NAME"),v=d("PATTERN");if(m||v){var T=h||"";i.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:m||c++,prefix:T,suffix:"",pattern:v||s,modifier:d("MODIFIER")||""});continue}var S=h||d("ESCAPED_CHAR");if(S){l+=S;continue}l&&(a.push(l),l="");var O=d("OPEN");if(O){var T=y(),j=d("NAME")||"",L=d("PATTERN")||"",ne=y();p("CLOSE"),a.push({name:j||(L?c++:""),pattern:j&&!L?s:L,prefix:T,suffix:ne,modifier:d("MODIFIER")||""});continue}p("END")}return a}o(bd,"parse");Ne.parse=bd;function LI(e,t){return Cy(bd(e,t),t)}o(LI,"compile");Ne.compile=LI;function Cy(e,t){t===void 0&&(t={});var r=_d(t),n=t.encode,i=n===void 0?function(u){return u}:n,s=t.validate,a=s===void 0?!0:s,c=e.map(function(u){if(typeof u=="object")return new RegExp("^(?:".concat(u.pattern,")$"),r)});return function(u){for(var l="",d=0;d<e.length;d++){var p=e[d];if(typeof p=="string"){l+=p;continue}var y=u?u[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",m=p.modifier==="*"||p.modifier==="+";if(Array.isArray(y)){if(!m)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(y.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var v=0;v<y.length;v++){var T=i(y[v],p);if(a&&!c[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof y=="string"||typeof y=="number"){var T=i(String(y),p);if(a&&!c[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!h){var S=m?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(S))}}return l}}o(Cy,"tokensToFunction");Ne.tokensToFunction=Cy;function DI(e,t){var r=[],n=Ed(e,r,t);return Ly(n,r,t)}o(DI,"match");Ne.match=DI;function Ly(e,t,r){r===void 0&&(r={});var n=r.decode,i=n===void 0?function(s){return s}:n;return function(s){var a=e.exec(s);if(!a)return!1;for(var c=a[0],u=a.index,l=Object.create(null),d=o(function(y){if(a[y]===void 0)return"continue";var h=t[y-1];h.modifier==="*"||h.modifier==="+"?l[h.name]=a[y].split(h.prefix+h.suffix).map(function(m){return i(m,h)}):l[h.name]=i(a[y],h)},"_loop_1"),p=1;p<a.length;p++)d(p);return{path:c,index:u,params:l}}}o(Ly,"regexpToFunction");Ne.regexpToFunction=Ly;function En(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}o(En,"escapeString");function _d(e){return e&&e.sensitive?"":"i"}o(_d,"flags");function UI(e,t){if(!t)return e;for(var r=/\((?:\?<(.*?)>)?(?!\?)/g,n=0,i=r.exec(e.source);i;)t.push({name:i[1]||n++,prefix:"",suffix:"",modifier:"",pattern:""}),i=r.exec(e.source);return e}o(UI,"regexpToRegexp");function MI(e,t,r){var n=e.map(function(i){return Ed(i,t,r).source});return new RegExp("(?:".concat(n.join("|"),")"),_d(r))}o(MI,"arrayToRegexp");function kI(e,t,r){return Dy(bd(e,r),t,r)}o(kI,"stringToRegexp");function Dy(e,t,r){r===void 0&&(r={});for(var n=r.strict,i=n===void 0?!1:n,s=r.start,a=s===void 0?!0:s,c=r.end,u=c===void 0?!0:c,l=r.encode,d=l===void 0?function(H){return H}:l,p=r.delimiter,y=p===void 0?"/#?":p,h=r.endsWith,m=h===void 0?"":h,v="[".concat(En(m),"]|$"),T="[".concat(En(y),"]"),S=a?"^":"",O=0,j=e;O<j.length;O++){var L=j[O];if(typeof L=="string")S+=En(d(L));else{var ne=En(d(L.prefix)),ie=En(d(L.suffix));if(L.pattern)if(t&&t.push(L),ne||ie)if(L.modifier==="+"||L.modifier==="*"){var ge=L.modifier==="*"?"?":"";S+="(?:".concat(ne,"((?:").concat(L.pattern,")(?:").concat(ie).concat(ne,"(?:").concat(L.pattern,"))*)").concat(ie,")").concat(ge)}else S+="(?:".concat(ne,"(").concat(L.pattern,")").concat(ie,")").concat(L.modifier);else L.modifier==="+"||L.modifier==="*"?S+="((?:".concat(L.pattern,")").concat(L.modifier,")"):S+="(".concat(L.pattern,")").concat(L.modifier);else S+="(?:".concat(ne).concat(ie,")").concat(L.modifier)}}if(u)i||(S+="".concat(T,"?")),S+=r.endsWith?"(?=".concat(v,")"):"$";else{var Be=e[e.length-1],E=typeof Be=="string"?T.indexOf(Be[Be.length-1])>-1:Be===void 0;i||(S+="(?:".concat(T,"(?=").concat(v,"))?")),E||(S+="(?=".concat(T,"|").concat(v,")"))}return new RegExp(S,_d(r))}o(Dy,"tokensToRegexp");Ne.tokensToRegexp=Dy;function Ed(e,t,r){return e instanceof RegExp?UI(e,t):Array.isArray(e)?MI(e,t,r):kI(e,t,r)}o(Ed,"pathToRegexp");Ne.pathToRegexp=Ed});var Sd=g(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.AwsV4Signer=wn.AwsClient=void 0;var HI=Sr(),Fy=D(),FI=(0,HI.debug)("zuplo:runtime"),vd=new TextEncoder,My={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"},qI=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Td=class{static{o(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:t,secretAccessKey:r,sessionToken:n,service:i,region:s,cache:a,retries:c,initRetryMs:u}){if(t==null)throw new TypeError("accessKeyId is a required option");if(r==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=t,this.secretAccessKey=r,this.sessionToken=n,this.service=i,this.region=s,this.cache=a||new Map,this.retries=c??0,this.initRetryMs=u||50}async sign(t,r){let n=new Fs(Object.assign({url:t},r,this,r&&r.aws)),i=Object.assign({},r,await n.sign());return delete i.aws,{url:i.url.toString(),request:i}}async fetch(t,r){FI("AWS fetch",t);for(let n=0;n<=this.retries;n++){let{url:i,request:s}=await this.sign(t,r),a=fetch(i,s);if(n===this.retries)return a;let c=await a;if(c.status<500&&c.status!==429)return c;await new Promise(u=>setTimeout(u,Math.random()*this.initRetryMs*Math.pow(2,n)))}throw new Fy.ConfigurationError("An unknown error occurred, ensure retries is not negative")}};wn.AwsClient=Td;var Fs=class{static{o(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:t,url:r,headers:n,body:i,accessKeyId:s,secretAccessKey:a,sessionToken:c,service:u,region:l,cache:d,datetime:p,signQuery:y,appendSessionToken:h,allHeaders:m,singleEncode:v}){if(r==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=t||(i?"POST":"GET"),this.url=new URL(r),this.headers=new Headers(n||{}),this.body=i,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=c;let T,S;(!u||!l)&&([T,S]=$I(this.url,this.headers)),this.service=u||T||"",this.region=l||S||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=y,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let O=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"),O.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&O.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(L=>m||!qI.includes(L)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(L=>L+":"+(L==="host"?this.url.host:(this.headers.get(L)||"").replace(/\s+/g," "))).join(`
59
+ -----END ${t}-----`},"default")});function jf(e){let t=[],r=0;for(;r<e.length;){let n=zf(e.subarray(r));t.push(n),r+=n.byteLength}return t}function zf(e){let t=0,r=e[0]&31;if(t++,r===31){for(r=0;e[t]>=128;)r=r*128+e[t]-128,t++;r=r*128+e[t]-128,t++}let n=0;if(e[t]<128)n=e[t],t++;else if(n===128){for(n=0;e[t+n]!==0||e[t+n+1]!==0;){if(n>e.byteLength)throw new TypeError("invalid indefinite form length");n++}let s=t+n+2;return{byteLength:s,contents:e.subarray(t,t+n),raw:e.subarray(0,s)}}else{let s=e[t]&127;t++,n=0;for(let a=0;a<s;a++)n=n*256+e[t],t++}let i=t+n;return{byteLength:i,contents:e.subarray(t,i),raw:e.subarray(0,i)}}function YT(e){let t=jf(jf(zf(e).contents)[0].contents);return Bo(t[t[0].raw[0]===160?6:5].raw)}function ZT(e){let t=e.replace(/(?:-----(?:BEGIN|END) CERTIFICATE-----|\s)/g,""),r=Zu(t);return pl(YT(r),"PUBLIC KEY")}var Vf,Gf,Bf,sr,$f,Kf,Jf,hl,Wf,ts=I(()=>{Ie();st();Re();qf();V();at();Vf=o(async(e,t,r)=>{if(!ae(r))throw new TypeError(oe(r,...W));if(!r.extractable)throw new TypeError("CryptoKey is not extractable");if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return pl(Bo(new Uint8Array(await U.subtle.exportKey(t,r))),`${e.toUpperCase()} KEY`)},"genericExport"),Gf=o(e=>Vf("public","spki",e),"toSPKI"),Bf=o(e=>Vf("private","pkcs8",e),"toPKCS8"),sr=o((e,t,r=0)=>{r===0&&(t.unshift(t.length),t.unshift(6));let n=e.indexOf(t[0],r);if(n===-1)return!1;let i=e.subarray(n,n+t.length);return i.length!==t.length?!1:i.every((s,a)=>s===t[a])||sr(e,t,n+1)},"findOid"),$f=o(e=>{switch(!0){case sr(e,[42,134,72,206,61,3,1,7]):return"P-256";case sr(e,[43,129,4,0,34]):return"P-384";case sr(e,[43,129,4,0,35]):return"P-521";case sr(e,[43,101,110]):return"X25519";case sr(e,[43,101,111]):return"X448";case sr(e,[43,101,112]):return"Ed25519";case sr(e,[43,101,113]):return"Ed448";default:throw new k("Invalid or unsupported EC Key Curve or OKP Key Sub Type")}},"getNamedCurve"),Kf=o(async(e,t,r,n,i)=>{var s;let a,c,u=new Uint8Array(atob(r.replace(e,"")).split("").map(d=>d.charCodeAt(0))),l=t==="spki";switch(n){case"PS256":case"PS384":case"PS512":a={name:"RSA-PSS",hash:`SHA-${n.slice(-3)}`},c=l?["verify"]:["sign"];break;case"RS256":case"RS384":case"RS512":a={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${n.slice(-3)}`},c=l?["verify"]:["sign"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":a={name:"RSA-OAEP",hash:`SHA-${parseInt(n.slice(-3),10)||1}`},c=l?["encrypt","wrapKey"]:["decrypt","unwrapKey"];break;case"ES256":a={name:"ECDSA",namedCurve:"P-256"},c=l?["verify"]:["sign"];break;case"ES384":a={name:"ECDSA",namedCurve:"P-384"},c=l?["verify"]:["sign"];break;case"ES512":a={name:"ECDSA",namedCurve:"P-521"},c=l?["verify"]:["sign"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let d=$f(u);a=d.startsWith("P-")?{name:"ECDH",namedCurve:d}:{name:d},c=l?[]:["deriveBits"];break}case"EdDSA":a={name:$f(u)},c=l?["verify"]:["sign"];break;default:throw new k('Invalid or unsupported "alg" (Algorithm) value')}return U.subtle.importKey(t,u,a,(s=i?.extractable)!==null&&s!==void 0?s:!1,c)},"genericImport"),Jf=o((e,t,r)=>Kf(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,"pkcs8",e,t,r),"fromPKCS8"),hl=o((e,t,r)=>Kf(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,"spki",e,t,r),"fromSPKI");o(jf,"getElement");o(zf,"parseElement");o(YT,"spkiFromX509");o(ZT,"getSPKI");Wf=o((e,t,r)=>{let n;try{n=ZT(e)}catch(i){throw new TypeError("failed to parse the X.509 certificate",{cause:i})}return hl(n,t,r)},"fromX509")});function XT(e){let t,r;switch(e.kty){case"oct":{switch(e.alg){case"HS256":case"HS384":case"HS512":t={name:"HMAC",hash:`SHA-${e.alg.slice(-3)}`},r=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":throw new k(`${e.alg} keys cannot be imported as CryptoKey instances`);case"A128GCM":case"A192GCM":case"A256GCM":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":t={name:"AES-GCM"},r=["encrypt","decrypt"];break;case"A128KW":case"A192KW":case"A256KW":t={name:"AES-KW"},r=["wrapKey","unwrapKey"];break;case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":t={name:"PBKDF2"},r=["deriveBits"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"RSA":{switch(e.alg){case"PS256":case"PS384":case"PS512":t={name:"RSA-PSS",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":t={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.alg.slice(-3)}`},r=e.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":t={name:"RSA-OAEP",hash:`SHA-${parseInt(e.alg.slice(-3),10)||1}`},r=e.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(e.alg){case"ES256":t={name:"ECDSA",namedCurve:"P-256"},r=e.d?["sign"]:["verify"];break;case"ES384":t={name:"ECDSA",namedCurve:"P-384"},r=e.d?["sign"]:["verify"];break;case"ES512":t={name:"ECDSA",namedCurve:"P-521"},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:"ECDH",namedCurve:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(e.alg){case"EdDSA":t={name:e.crv},r=e.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":t={name:e.crv},r=e.d?["deriveBits"]:[];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new k('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:t,keyUsages:r}}var eS,fl,Qf=I(()=>{Ie();V();Re();o(XT,"subtleMapping");eS=o(async e=>{var t,r;if(!e.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:n,keyUsages:i}=XT(e),s=[n,(t=e.ext)!==null&&t!==void 0?t:!1,(r=e.key_ops)!==null&&r!==void 0?r:i];if(n.name==="PBKDF2")return U.subtle.importKey("raw",te(e.k),...s);let a={...e};return delete a.alg,delete a.use,U.subtle.importKey("jwk",a,...s)},"parse"),fl=eS});async function Yf(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return hl(e,t,r)}async function Zf(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return Wf(e,t,r)}async function Xf(e,t,r){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return Jf(e,t,r)}async function ar(e,t,r){var n;if(!Q(e))throw new TypeError("JWK must be an object");switch(t||(t=e.alg),e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return r??(r=e.ext!==!0),r?fl({...e,alg:t,ext:(n=e.ext)!==null&&n!==void 0?n:!1}):te(e.k);case"RSA":if(e.oth!==void 0)throw new k('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return fl({...e,alg:t});default:throw new k('Unsupported "kty" (Key Type) Parameter value')}}var di=I(()=>{Re();ts();Qf();V();$e();o(Yf,"importSPKI");o(Zf,"importX509");o(Xf,"importPKCS8");o(ar,"importJWK")});var tS,rS,nS,cr,pi=I(()=>{st();at();tS=o((e,t)=>{if(!(t instanceof Uint8Array)){if(!il(t))throw new TypeError(nl(e,t,...W,"Uint8Array"));if(t.type!=="secret")throw new TypeError(`${W.join(" or ")} instances for symmetric algorithms must be of type "secret"`)}},"symmetricTypeCheck"),rS=o((e,t,r)=>{if(!il(t))throw new TypeError(nl(e,t,...W));if(t.type==="secret")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&t.type==="public")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&t.type==="public")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&r==="verify"&&t.type==="private")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&r==="encrypt"&&t.type==="private")throw new TypeError(`${W.join(" or ")} instances for asymmetric algorithm encryption must be of type "public"`)},"asymmetricTypeCheck"),nS=o((e,t,r)=>{e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?tS(e,t):rS(e,t,r)},"checkKeyType"),cr=nS});async function iS(e,t,r,n,i){if(!(r instanceof Uint8Array))throw new TypeError(oe(r,"Uint8Array"));let s=parseInt(e.slice(1,4),10),a=await U.subtle.importKey("raw",r.subarray(s>>3),"AES-CBC",!1,["encrypt"]),c=await U.subtle.importKey("raw",r.subarray(0,s>>3),{hash:`SHA-${s<<1}`,name:"HMAC"},!1,["sign"]),u=new Uint8Array(await U.subtle.encrypt({iv:n,name:"AES-CBC"},a,t)),l=Ae(i,n,u,jo(i.length<<3)),d=new Uint8Array((await U.subtle.sign("HMAC",c,l)).slice(0,s>>3));return{ciphertext:u,tag:d}}async function oS(e,t,r,n,i){let s;r instanceof Uint8Array?s=await U.subtle.importKey("raw",r,"AES-GCM",!1,["encrypt"]):(qe(r,e,"encrypt"),s=r);let a=new Uint8Array(await U.subtle.encrypt({additionalData:i,iv:n,name:"AES-GCM",tagLength:128},s,t)),c=a.slice(-16);return{ciphertext:a.slice(0,-16),tag:c}}var sS,hi,ml=I(()=>{_e();tl();rl();Ie();or();st();V();at();o(iS,"cbcEncrypt");o(oS,"gcmEncrypt");sS=o(async(e,t,r,n,i)=>{if(!ae(r)&&!(r instanceof Uint8Array))throw new TypeError(oe(r,...W,"Uint8Array"));switch(zo(e,n),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return r instanceof Uint8Array&&tn(r,parseInt(e.slice(-3),10)),iS(e,t,r,n,i);case"A128GCM":case"A192GCM":case"A256GCM":return r instanceof Uint8Array&&tn(r,parseInt(e.slice(1,4),10)),oS(e,t,r,n,i);default:throw new k("Unsupported JWE Content Encryption Algorithm")}},"encrypt"),hi=sS});async function em(e,t,r,n){let i=e.slice(0,7);n||(n=Ko(i));let{ciphertext:s,tag:a}=await hi(i,r,t,n,new Uint8Array(0));return{encryptedKey:s,iv:Z(n),tag:Z(a)}}async function tm(e,t,r,n,i){let s=e.slice(0,7);return Qo(s,t,r,n,i,new Uint8Array(0))}var yl=I(()=>{ml();ol();Jo();Re();o(em,"wrap");o(tm,"unwrap")});async function aS(e,t,r,n,i){switch(cr(e,t,"decrypt"),e){case"dir":{if(r!==void 0)throw new R("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(r!==void 0)throw new R("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Q(n.epk))throw new R('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!Xo(t))throw new k("ECDH with the provided key is not allowed or not supported by your javascript runtime");let s=await ar(n.epk,e),a,c;if(n.apu!==void 0){if(typeof n.apu!="string")throw new R('JOSE Header "apu" (Agreement PartyUInfo) invalid');a=te(n.apu)}if(n.apv!==void 0){if(typeof n.apv!="string")throw new R('JOSE Header "apv" (Agreement PartyVInfo) invalid');c=te(n.apv)}let u=await Zo(s,t,e==="ECDH-ES"?n.enc:e,e==="ECDH-ES"?ui(n.enc):parseInt(e.slice(-5,-2),10),a,c);if(e==="ECDH-ES")return u;if(r===void 0)throw new R("JWE Encrypted Key missing");return ci(e.slice(-6),u,r)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(r===void 0)throw new R("JWE Encrypted Key missing");return Ff(e,t,r)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(r===void 0)throw new R("JWE Encrypted Key missing");if(typeof n.p2c!="number")throw new R('JOSE Header "p2c" (PBES2 Count) missing or invalid');let s=i?.maxPBES2Count||1e4;if(n.p2c>s)throw new R('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof n.p2s!="string")throw new R('JOSE Header "p2s" (PBES2 Salt) missing or invalid');return Mf(e,t,r,n.p2c,te(n.p2s))}case"A128KW":case"A192KW":case"A256KW":{if(r===void 0)throw new R("JWE Encrypted Key missing");return ci(e,t,r)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(r===void 0)throw new R("JWE Encrypted Key missing");if(typeof n.iv!="string")throw new R('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof n.tag!="string")throw new R('JOSE Header "tag" (Authentication Tag) missing or invalid');let s=te(n.iv),a=te(n.tag);return tm(e,t,r,s,a)}default:throw new k('Invalid or unsupported "alg" (JWE Algorithm) header value')}}var rm,nm=I(()=>{Yo();cl();ll();dl();Re();V();li();di();pi();$e();yl();o(aS,"decryptKeyManagement");rm=aS});function cS(e,t,r,n,i){if(i.crit!==void 0&&n.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(a=>typeof a!="string"||a.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let s;r!==void 0?s=new Map([...Object.entries(r),...t.entries()]):s=t;for(let a of n.crit){if(!s.has(a))throw new k(`Extension Header Parameter "${a}" is not recognized`);if(i[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(s.get(a)&&n[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(n.crit)}var Et,sn=I(()=>{V();o(cS,"validateCrit");Et=cS});var uS,fi,gl=I(()=>{uS=o((e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(r=>typeof r!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)},"validateAlgorithms"),fi=uS});async function an(e,t,r){var n;if(!Q(e))throw new R("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new R("JOSE Header missing");if(typeof e.iv!="string")throw new R("JWE Initialization Vector missing or incorrect type");if(typeof e.ciphertext!="string")throw new R("JWE Ciphertext missing or incorrect type");if(typeof e.tag!="string")throw new R("JWE Authentication Tag missing or incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new R("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new R("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new R("JWE AAD incorrect type");if(e.header!==void 0&&!Q(e.header))throw new R("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!Q(e.unprotected))throw new R("JWE Per-Recipient Unprotected Header incorrect type");let i;if(e.protected)try{let j=te(e.protected);i=JSON.parse(ue.decode(j))}catch{throw new R("JWE Protected Header is invalid")}if(!bt(i,e.header,e.unprotected))throw new R("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let s={...i,...e.header,...e.unprotected};if(Et(R,new Map,r?.crit,i,s),s.zip!==void 0){if(!i||!i.zip)throw new R('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(s.zip!=="DEF")throw new k('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:a,enc:c}=s;if(typeof a!="string"||!a)throw new R("missing JWE Algorithm (alg) in JWE Header");if(typeof c!="string"||!c)throw new R("missing JWE Encryption Algorithm (enc) in JWE Header");let u=r&&fi("keyManagementAlgorithms",r.keyManagementAlgorithms),l=r&&fi("contentEncryptionAlgorithms",r.contentEncryptionAlgorithms);if(u&&!u.has(a))throw new tr('"alg" (Algorithm) Header Parameter not allowed');if(l&&!l.has(c))throw new tr('"enc" (Encryption Algorithm) Header Parameter not allowed');let d;e.encrypted_key!==void 0&&(d=te(e.encrypted_key));let p=!1;typeof t=="function"&&(t=await t(i,e),p=!0);let y;try{y=await rm(a,t,d,s,r)}catch(j){if(j instanceof TypeError||j instanceof R||j instanceof k)throw j;y=_t(c)}let h=te(e.iv),m=te(e.tag),v=Y.encode((n=e.protected)!==null&&n!==void 0?n:""),T;e.aad!==void 0?T=Ae(v,Y.encode("."),Y.encode(e.aad)):T=v;let S=await Qo(c,y,te(e.ciphertext),h,m,T);s.zip==="DEF"&&(S=await(r?.inflateRaw||Rf)(S));let O={plaintext:S};return e.protected!==void 0&&(O.protectedHeader=i),e.aad!==void 0&&(O.additionalAuthenticatedData=te(e.aad)),e.unprotected!==void 0&&(O.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(O.unprotectedHeader=e.header),p?{...O,key:t}:O}var rs=I(()=>{Re();ol();sl();V();rn();$e();nm();_e();li();sn();gl();o(an,"flattenedDecrypt")});async function ns(e,t,r){if(e instanceof Uint8Array&&(e=ue.decode(e)),typeof e!="string")throw new R("Compact JWE must be a string or Uint8Array");let{0:n,1:i,2:s,3:a,4:c,length:u}=e.split(".");if(u!==5)throw new R("Invalid Compact JWE");let l=await an({ciphertext:a,iv:s||void 0,protected:n||void 0,tag:c||void 0,encrypted_key:i||void 0},t,r),d={plaintext:l.plaintext,protectedHeader:l.protectedHeader};return typeof t=="function"?{...d,key:l.key}:d}var bl=I(()=>{rs();V();_e();o(ns,"compactDecrypt")});async function im(e,t,r){if(!Q(e))throw new R("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(Q))throw new R("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new R("JWE Recipients has no members");for(let n of e.recipients)try{return await an({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:n.encrypted_key,header:n.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,r)}catch{}throw new Ut}var om=I(()=>{rs();V();$e();o(im,"generalDecrypt")});var lS,sm,am=I(()=>{Ie();st();Re();at();lS=o(async e=>{if(e instanceof Uint8Array)return{kty:"oct",k:Z(e)};if(!ae(e))throw new TypeError(oe(e,...W,"Uint8Array"));if(!e.extractable)throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");let{ext:t,key_ops:r,alg:n,use:i,...s}=await U.subtle.exportKey("jwk",e);return s},"keyToJWK"),sm=lS});async function cm(e){return Gf(e)}async function um(e){return Bf(e)}async function is(e){return sm(e)}var _l=I(()=>{ts();ts();am();o(cm,"exportSPKI");o(um,"exportPKCS8");o(is,"exportJWK")});async function dS(e,t,r,n,i={}){let s,a,c;switch(cr(e,r,"encrypt"),e){case"dir":{c=r;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!Xo(r))throw new k("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:u,apv:l}=i,{epk:d}=i;d||(d=(await xf(r)).privateKey);let{x:p,y,crv:h,kty:m}=await is(d),v=await Zo(r,d,e==="ECDH-ES"?t:e,e==="ECDH-ES"?ui(t):parseInt(e.slice(-5,-2),10),u,l);if(a={epk:{x:p,crv:h,kty:m}},m==="EC"&&(a.epk.y=y),u&&(a.apu=Z(u)),l&&(a.apv=Z(l)),e==="ECDH-ES"){c=v;break}c=n||_t(t);let T=e.slice(-6);s=await ai(T,v,c);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{c=n||_t(t),s=await Hf(e,r,c);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{c=n||_t(t);let{p2c:u,p2s:l}=i;({encryptedKey:s,...a}=await Uf(e,r,c,u,l));break}case"A128KW":case"A192KW":case"A256KW":{c=n||_t(t),s=await ai(e,r,c);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{c=n||_t(t);let{iv:u}=i;({encryptedKey:s,...a}=await em(e,r,c,u));break}default:throw new k('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:c,encryptedKey:s,parameters:a}}var os,El=I(()=>{Yo();cl();ll();dl();Re();li();V();_l();pi();yl();o(dS,"encryptKeyManagement");os=dS});var wl,Mt,ss=I(()=>{Re();ml();sl();Jo();El();V();rn();_e();sn();wl=Symbol(),Mt=class{static{o(this,"FlattenedEncrypt")}constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,r){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new R("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!bt(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new R("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if(Et(R,new Map,r?.crit,this._protectedHeader,n),n.zip!==void 0){if(!this._protectedHeader||!this._protectedHeader.zip)throw new R('JWE "zip" (Compression Algorithm) Header MUST be integrity protected');if(n.zip!=="DEF")throw new k('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value')}let{alg:i,enc:s}=n;if(typeof i!="string"||!i)throw new R('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof s!="string"||!s)throw new R('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let a;if(i==="dir"){if(this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Encryption")}else if(i==="ECDH-ES"&&this._cek)throw new TypeError("setContentEncryptionKey cannot be called when using Direct Key Agreement");let c;{let m;({cek:c,encryptedKey:a,parameters:m}=await os(i,s,t,this._cek,this._keyManagementParameters)),m&&(r&&wl in r?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...m}:this.setUnprotectedHeader(m):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...m}:this.setProtectedHeader(m))}this._iv||(this._iv=Ko(s));let u,l,d;this._protectedHeader?l=Y.encode(Z(JSON.stringify(this._protectedHeader))):l=Y.encode(""),this._aad?(d=Z(this._aad),u=Ae(l,Y.encode("."),Y.encode(d))):u=l;let p,y;if(n.zip==="DEF"){let m=await(r?.deflateRaw||Pf)(this._plaintext);({ciphertext:p,tag:y}=await hi(s,m,c,this._iv,u))}else({ciphertext:p,tag:y}=await hi(s,this._plaintext,c,this._iv,u));let h={ciphertext:Z(p),iv:Z(this._iv),tag:Z(y)};return a&&(h.encrypted_key=Z(a)),d&&(h.aad=d),this._protectedHeader&&(h.protected=ue.decode(l)),this._sharedUnprotectedHeader&&(h.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(h.header=this._unprotectedHeader),h}}});var vl,as,lm=I(()=>{ss();V();li();rn();El();Re();sn();vl=class{static{o(this,"IndividualRecipient")}constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},as=class{static{o(this,"GeneralEncrypt")}constructor(t){this._recipients=[],this._plaintext=t}addRecipient(t,r){let n=new vl(this,t,{crit:r?.crit});return this._recipients.push(n),n}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(t){var r,n,i;if(!this._recipients.length)throw new R("at least one recipient must be added");if(t={deflateRaw:t?.deflateRaw},this._recipients.length===1){let[u]=this._recipients,l=await new Mt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(u.unprotectedHeader).encrypt(u.key,{...u.options,...t}),d={ciphertext:l.ciphertext,iv:l.iv,recipients:[{}],tag:l.tag};return l.aad&&(d.aad=l.aad),l.protected&&(d.protected=l.protected),l.unprotected&&(d.unprotected=l.unprotected),l.encrypted_key&&(d.recipients[0].encrypted_key=l.encrypted_key),l.header&&(d.recipients[0].header=l.header),d}let s;for(let u=0;u<this._recipients.length;u++){let l=this._recipients[u];if(!bt(this._protectedHeader,this._unprotectedHeader,l.unprotectedHeader))throw new R("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let d={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader},{alg:p}=d;if(typeof p!="string"||!p)throw new R('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(p==="dir"||p==="ECDH-ES")throw new R('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof d.enc!="string"||!d.enc)throw new R('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!s)s=d.enc;else if(s!==d.enc)throw new R('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if(Et(R,new Map,l.options.crit,this._protectedHeader,d),d.zip!==void 0&&(!this._protectedHeader||!this._protectedHeader.zip))throw new R('JWE "zip" (Compression Algorithm) Header MUST be integrity protected')}let a=_t(s),c={ciphertext:"",iv:"",recipients:[],tag:""};for(let u=0;u<this._recipients.length;u++){let l=this._recipients[u],d={};c.recipients.push(d);let y={...this._protectedHeader,...this._unprotectedHeader,...l.unprotectedHeader}.alg.startsWith("PBES2")?2048+u:void 0;if(u===0){let v=await new Mt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(a).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(l.unprotectedHeader).setKeyManagementParameters({p2c:y}).encrypt(l.key,{...l.options,...t,[wl]:!0});c.ciphertext=v.ciphertext,c.iv=v.iv,c.tag=v.tag,v.aad&&(c.aad=v.aad),v.protected&&(c.protected=v.protected),v.unprotected&&(c.unprotected=v.unprotected),d.encrypted_key=v.encrypted_key,v.header&&(d.header=v.header);continue}let{encryptedKey:h,parameters:m}=await os(((r=l.unprotectedHeader)===null||r===void 0?void 0:r.alg)||((n=this._protectedHeader)===null||n===void 0?void 0:n.alg)||((i=this._unprotectedHeader)===null||i===void 0?void 0:i.alg),s,l.key,a,{p2c:y});d.encrypted_key=Z(h),(l.unprotectedHeader||m)&&(d.header={...l.unprotectedHeader,...m})}return c}}});function mi(e,t){let r=`SHA-${e.slice(-3)}`;switch(e){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:e.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:t.namedCurve};case"EdDSA":return{name:t.name};default:throw new k(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}var Tl=I(()=>{V();o(mi,"subtleDsa")});function yi(e,t,r){if(ae(t))return If(t,e,r),t;if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError(oe(t,...W));return U.subtle.importKey("raw",t,{hash:`SHA-${e.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(oe(t,...W,"Uint8Array"))}var Sl=I(()=>{Ie();or();st();at();o(yi,"getCryptoKey")});var pS,dm,pm=I(()=>{Tl();Ie();es();Sl();pS=o(async(e,t,r,n)=>{let i=await yi(e,t,"verify");Dr(e,i);let s=mi(e,i.algorithm);try{return await U.subtle.verify(s,i,r,n)}catch{return!1}},"verify"),dm=pS});async function cn(e,t,r){var n;if(!Q(e))throw new z("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new z('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new z("JWS Protected Header incorrect type");if(e.payload===void 0)throw new z("JWS Payload missing");if(typeof e.signature!="string")throw new z("JWS Signature missing or incorrect type");if(e.header!==void 0&&!Q(e.header))throw new z("JWS Unprotected Header incorrect type");let i={};if(e.protected)try{let T=te(e.protected);i=JSON.parse(ue.decode(T))}catch{throw new z("JWS Protected Header is invalid")}if(!bt(i,e.header))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let s={...i,...e.header},a=Et(z,new Map([["b64",!0]]),r?.crit,i,s),c=!0;if(a.has("b64")&&(c=i.b64,typeof c!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:u}=s;if(typeof u!="string"||!u)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');let l=r&&fi("algorithms",r.algorithms);if(l&&!l.has(u))throw new tr('"alg" (Algorithm) Header Parameter not allowed');if(c){if(typeof e.payload!="string")throw new z("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new z("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"&&(t=await t(i,e),d=!0),cr(u,t,"verify");let p=Ae(Y.encode((n=e.protected)!==null&&n!==void 0?n:""),Y.encode("."),typeof e.payload=="string"?Y.encode(e.payload):e.payload),y=te(e.signature);if(!await dm(u,t,y,p))throw new Lr;let m;c?m=te(e.payload):typeof e.payload=="string"?m=Y.encode(e.payload):m=e.payload;let v={payload:m};return e.protected!==void 0&&(v.protectedHeader=i),e.header!==void 0&&(v.unprotectedHeader=e.header),d?{...v,key:t}:v}var cs=I(()=>{Re();pm();V();_e();rn();$e();pi();sn();gl();o(cn,"flattenedVerify")});async function us(e,t,r){if(e instanceof Uint8Array&&(e=ue.decode(e)),typeof e!="string")throw new z("Compact JWS must be a string or Uint8Array");let{0:n,1:i,2:s,length:a}=e.split(".");if(a!==3)throw new z("Invalid Compact JWS");let c=await cn({payload:i,protected:n,signature:s},t,r),u={payload:c.payload,protectedHeader:c.protectedHeader};return typeof t=="function"?{...u,key:c.key}:u}var Il=I(()=>{cs();V();_e();o(us,"compactVerify")});async function hm(e,t,r){if(!Q(e))throw new z("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(Q))throw new z("JWS Signatures missing or incorrect type");for(let n of e.signatures)try{return await cn({header:n.header,payload:e.payload,protected:n.protected,signature:n.signature},t,r)}catch{}throw new Lr}var fm=I(()=>{cs();V();$e();o(hm,"generalVerify")});var un,Al=I(()=>{un=o(e=>Math.floor(e.getTime()/1e3),"default")});var hS,ln,Rl=I(()=>{hS=/^(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)$/i,ln=o(e=>{let t=hS.exec(e);if(!t)throw new TypeError("Invalid time period format");let r=parseFloat(t[1]);switch(t[2].toLowerCase()){case"sec":case"secs":case"second":case"seconds":case"s":return Math.round(r);case"minute":case"minutes":case"min":case"mins":case"m":return Math.round(r*60);case"hour":case"hours":case"hr":case"hrs":case"h":return Math.round(r*3600);case"day":case"days":case"d":return Math.round(r*86400);case"week":case"weeks":case"w":return Math.round(r*604800);default:return Math.round(r*31557600)}},"default")});var mm,fS,dn,ls=I(()=>{V();_e();Al();Rl();$e();mm=o(e=>e.toLowerCase().replace(/^application\//,""),"normalizeTyp"),fS=o((e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1,"checkAudiencePresence"),dn=o((e,t,r={})=>{let{typ:n}=r;if(n&&(typeof e.typ!="string"||mm(e.typ)!==mm(n)))throw new Ee('unexpected "typ" JWT header value',"typ","check_failed");let i;try{i=JSON.parse(ue.decode(t))}catch{}if(!Q(i))throw new pe("JWT Claims Set must be a top-level JSON object");let{requiredClaims:s=[],issuer:a,subject:c,audience:u,maxTokenAge:l}=r;l!==void 0&&s.push("iat"),u!==void 0&&s.push("aud"),c!==void 0&&s.push("sub"),a!==void 0&&s.push("iss");for(let h of new Set(s.reverse()))if(!(h in i))throw new Ee(`missing required "${h}" claim`,h,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(i.iss))throw new Ee('unexpected "iss" claim value',"iss","check_failed");if(c&&i.sub!==c)throw new Ee('unexpected "sub" claim value',"sub","check_failed");if(u&&!fS(i.aud,typeof u=="string"?[u]:u))throw new Ee('unexpected "aud" claim value',"aud","check_failed");let d;switch(typeof r.clockTolerance){case"string":d=ln(r.clockTolerance);break;case"number":d=r.clockTolerance;break;case"undefined":d=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:p}=r,y=un(p||new Date);if((i.iat!==void 0||l)&&typeof i.iat!="number")throw new Ee('"iat" claim must be a number',"iat","invalid");if(i.nbf!==void 0){if(typeof i.nbf!="number")throw new Ee('"nbf" claim must be a number',"nbf","invalid");if(i.nbf>y+d)throw new Ee('"nbf" claim timestamp check failed',"nbf","check_failed")}if(i.exp!==void 0){if(typeof i.exp!="number")throw new Ee('"exp" claim must be a number',"exp","invalid");if(i.exp<=y-d)throw new en('"exp" claim timestamp check failed',"exp","check_failed")}if(l){let h=y-i.iat,m=typeof l=="number"?l:ln(l);if(h-d>m)throw new en('"iat" claim timestamp check failed (too far in the past)',"iat","check_failed");if(h<0-d)throw new Ee('"iat" claim timestamp check failed (it should be in the past)',"iat","check_failed")}return i},"default")});async function ym(e,t,r){var n;let i=await us(e,t,r);if(!((n=i.protectedHeader.crit)===null||n===void 0)&&n.includes("b64")&&i.protectedHeader.b64===!1)throw new pe("JWTs MUST NOT use unencoded payload");let a={payload:dn(i.protectedHeader,i.payload,r),protectedHeader:i.protectedHeader};return typeof t=="function"?{...a,key:i.key}:a}var gm=I(()=>{Il();ls();V();o(ym,"jwtVerify")});async function bm(e,t,r){let n=await ns(e,t,r),i=dn(n.protectedHeader,n.plaintext,r),{protectedHeader:s}=n;if(s.iss!==void 0&&s.iss!==i.iss)throw new Ee('replicated "iss" claim header parameter mismatch',"iss","mismatch");if(s.sub!==void 0&&s.sub!==i.sub)throw new Ee('replicated "sub" claim header parameter mismatch',"sub","mismatch");if(s.aud!==void 0&&JSON.stringify(s.aud)!==JSON.stringify(i.aud))throw new Ee('replicated "aud" claim header parameter mismatch',"aud","mismatch");let a={payload:i,protectedHeader:s};return typeof t=="function"?{...a,key:n.key}:a}var _m=I(()=>{bl();ls();V();o(bm,"jwtDecrypt")});var pn,Pl=I(()=>{ss();pn=class{static{o(this,"CompactEncrypt")}constructor(t){this._flattened=new Mt(t)}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,r){let n=await this._flattened.encrypt(t,r);return[n.protected,n.encrypted_key,n.iv,n.ciphertext,n.tag].join(".")}}});var mS,Em,wm=I(()=>{Tl();Ie();es();Sl();mS=o(async(e,t,r)=>{let n=await yi(e,t,"sign");Dr(e,n);let i=await U.subtle.sign(mi(e,n.algorithm),n,r);return new Uint8Array(i)},"sign"),Em=mS});var ur,ds=I(()=>{Re();wm();rn();V();_e();pi();sn();ur=class{static{o(this,"FlattenedSign")}constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new z("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!bt(this._protectedHeader,this._unprotectedHeader))throw new z("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},i=Et(z,new Map([["b64",!0]]),r?.crit,this._protectedHeader,n),s=!0;if(i.has("b64")&&(s=this._protectedHeader.b64,typeof s!="boolean"))throw new z('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=n;if(typeof a!="string"||!a)throw new z('JWS "alg" (Algorithm) Header Parameter missing or invalid');cr(a,t,"sign");let c=this._payload;s&&(c=Y.encode(Z(c)));let u;this._protectedHeader?u=Y.encode(Z(JSON.stringify(this._protectedHeader))):u=Y.encode("");let l=Ae(u,Y.encode("."),c),d=await Em(a,t,l),p={signature:Z(d),payload:""};return s&&(p.payload=ue.decode(c)),this._unprotectedHeader&&(p.header=this._unprotectedHeader),this._protectedHeader&&(p.protected=ue.decode(u)),p}}});var hn,Ol=I(()=>{ds();hn=class{static{o(this,"CompactSign")}constructor(t){this._flattened=new ur(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,r){let n=await this._flattened.sign(t,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}}});var Nl,ps,vm=I(()=>{ds();V();Nl=class{static{o(this,"IndividualSignature")}constructor(t,r,n){this.parent=t,this.key=r,this.options=n}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},ps=class{static{o(this,"GeneralSign")}constructor(t){this._signatures=[],this._payload=t}addSignature(t,r){let n=new Nl(this,t,r);return this._signatures.push(n),n}async sign(){if(!this._signatures.length)throw new z("at least one signature must be added");let t={signatures:[],payload:""};for(let r=0;r<this._signatures.length;r++){let n=this._signatures[r],i=new ur(this._payload);i.setProtectedHeader(n.protectedHeader),i.setUnprotectedHeader(n.unprotectedHeader);let{payload:s,...a}=await i.sign(n.key,n.options);if(r===0)t.payload=s;else if(t.payload!==s)throw new z("inconsistent use of JWS Unencoded Payload (RFC7797)");t.signatures.push(a)}return t}}});var lr,hs=I(()=>{Al();$e();Rl();lr=class{static{o(this,"ProduceJWT")}constructor(t){if(!Q(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:t}:this._payload={...this._payload,nbf:un(new Date)+ln(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:t}:this._payload={...this._payload,exp:un(new Date)+ln(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:un(new Date)}:this._payload={...this._payload,iat:t},this}}});var fs,Tm=I(()=>{Ol();V();_e();hs();fs=class extends lr{static{o(this,"SignJWT")}setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,r){var n;let i=new hn(Y.encode(JSON.stringify(this._payload)));if(i.setProtectedHeader(this._protectedHeader),Array.isArray((n=this._protectedHeader)===null||n===void 0?void 0:n.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new pe("JWTs MUST NOT use unencoded payload");return i.sign(t,r)}}});var ms,Sm=I(()=>{Pl();_e();hs();ms=class extends lr{static{o(this,"EncryptJWT")}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(t,r){let n=new pn(Y.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),n.setProtectedHeader(this._protectedHeader),this._iv&&n.setInitializationVector(this._iv),this._cek&&n.setContentEncryptionKey(this._cek),this._keyManagementParameters&&n.setKeyManagementParameters(this._keyManagementParameters),n.encrypt(t,r)}}});async function xl(e,t){if(!Q(e))throw new TypeError("JWK must be an object");if(t??(t="sha256"),t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let r;switch(e.kty){case"EC":dr(e.crv,'"crv" (Curve) Parameter'),dr(e.x,'"x" (X Coordinate) Parameter'),dr(e.y,'"y" (Y Coordinate) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":dr(e.crv,'"crv" (Subtype of Key Pair) Parameter'),dr(e.x,'"x" (Public Key) Parameter'),r={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":dr(e.e,'"e" (Exponent) Parameter'),dr(e.n,'"n" (Modulus) Parameter'),r={e:e.e,kty:e.kty,n:e.n};break;case"oct":dr(e.k,'"k" (Key Value) Parameter'),r={k:e.k,kty:e.kty};break;default:throw new k('"kty" (Key Type) Parameter missing or unsupported')}let n=Y.encode(JSON.stringify(r));return Z(await qo(t,n))}async function Im(e,t){t??(t="sha256");let r=await xl(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${r}`}var dr,Am=I(()=>{Qu();Re();V();_e();$e();dr=o((e,t)=>{if(typeof e!="string"||!e)throw new ni(`${t} missing or invalid`)},"check");o(xl,"calculateJwkThumbprint");o(Im,"calculateJwkThumbprintUri")});async function Rm(e,t){let r={...e,...t?.header};if(!Q(r.jwk))throw new z('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let n=await ar({...r.jwk,ext:!0},r.alg,!0);if(n instanceof Uint8Array||n.type!=="public")throw new z('"jwk" (JSON Web Key) Header Parameter must be a public key');return n}var Pm=I(()=>{di();$e();V();o(Rm,"EmbeddedJWK")});function yS(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new k('Unsupported "alg" value for a JSON Web Key Set')}}function Cl(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(gS)}function gS(e){return Q(e)}function bS(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}async function Om(e,t,r){let n=e.get(t)||e.set(t,{}).get(t);if(n[r]===void 0){let i=await ar({...t,ext:!0},r);if(i instanceof Uint8Array||i.type!=="public")throw new rr("JSON Web Key Set members must be public keys");n[r]=i}return n[r]}function Nm(e){let t=new gi(e);return async function(r,n){return t.getKey(r,n)}}var gi,Ll=I(()=>{di();V();$e();o(yS,"getKtyFromAlg");o(Cl,"isJWKSLike");o(gS,"isJWKLike");o(bS,"clone");gi=class{static{o(this,"LocalJWKSet")}constructor(t){if(this._cached=new WeakMap,!Cl(t))throw new rr("JSON Web Key Set malformed");this._jwks=bS(t)}async getKey(t,r){let{alg:n,kid:i}={...t,...r?.header},s=yS(n),a=this._jwks.keys.filter(l=>{let d=s===l.kty;if(d&&typeof i=="string"&&(d=i===l.kid),d&&typeof l.alg=="string"&&(d=n===l.alg),d&&typeof l.use=="string"&&(d=l.use==="sig"),d&&Array.isArray(l.key_ops)&&(d=l.key_ops.includes("verify")),d&&n==="EdDSA"&&(d=l.crv==="Ed25519"||l.crv==="Ed448"),d)switch(n){case"ES256":d=l.crv==="P-256";break;case"ES256K":d=l.crv==="secp256k1";break;case"ES384":d=l.crv==="P-384";break;case"ES512":d=l.crv==="P-521";break}return d}),{0:c,length:u}=a;if(u===0)throw new Cr;if(u!==1){let l=new ii,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(let p of a)try{yield await Om(d,p,n)}catch{continue}},l}return Om(this._cached,c,n)}};o(Om,"importWithAlgCache");o(Nm,"createLocalJWKSet")});var _S,xm,Cm=I(()=>{V();_S=o(async(e,t,r)=>{let n,i,s=!1;typeof AbortController=="function"&&(n=new AbortController,i=setTimeout(()=>{s=!0,n.abort()},t));let a=await fetch(e.href,{signal:n?n.signal:void 0,redirect:"manual",headers:r.headers}).catch(c=>{throw s?new oi:c});if(i!==void 0&&clearTimeout(i),a.status!==200)throw new me("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await a.json()}catch{throw new me("Failed to parse the JSON Web Key Set HTTP response as JSON")}},"fetchJwks"),xm=_S});function ES(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}function Lm(e,t){let r=new Dl(e,t);return async function(n,i){return r.getKey(n,i)}}var Dl,Dm=I(()=>{Cm();V();Ll();o(ES,"isCloudflareWorkers");Dl=class extends gi{static{o(this,"RemoteJWKSet")}constructor(t,r){if(super({keys:[]}),this._jwks=void 0,!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.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}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(t,r){(!this._jwks||!this.fresh())&&await this.reload();try{return await super.getKey(t,r)}catch(n){if(n instanceof Cr&&this.coolingDown()===!1)return await this.reload(),super.getKey(t,r);throw n}}async reload(){this._pendingFetch&&ES()&&(this._pendingFetch=void 0),this._pendingFetch||(this._pendingFetch=xm(this._url,this._timeoutDuration,this._options).then(t=>{if(!Cl(t))throw new rr("JSON Web Key Set malformed");this._jwks={keys:t.keys},this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(t=>{throw this._pendingFetch=void 0,t})),await this._pendingFetch}};o(Lm,"createRemoteJWKSet")});var ys,Um=I(()=>{Re();_e();V();ls();hs();ys=class extends lr{static{o(this,"UnsecuredJWT")}encode(){let t=Z(JSON.stringify({alg:"none"})),r=Z(JSON.stringify(this._payload));return`${t}.${r}.`}static decode(t,r){if(typeof t!="string")throw new pe("Unsecured JWT must be a string");let{0:n,1:i,2:s,length:a}=t.split(".");if(a!==3||s!=="")throw new pe("Invalid Unsecured JWT");let c;try{if(c=JSON.parse(ue.decode(te(n))),c.alg!=="none")throw new Error}catch{throw new pe("Invalid Unsecured JWT")}return{payload:dn(c,te(i),r),header:c}}}});var Ul={};Wi(Ul,{decode:()=>bi,encode:()=>wS});var wS,bi,gs=I(()=>{Re();wS=Z,bi=te});function Mm(e){let t;if(typeof e=="string"){let r=e.split(".");(r.length===3||r.length===5)&&([t]=r)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let r=JSON.parse(ue.decode(bi(t)));if(!Q(r))throw new Error;return r}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}var km=I(()=>{gs();_e();$e();o(Mm,"decodeProtectedHeader")});function Hm(e){if(typeof e!="string")throw new pe("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:r}=e.split(".");if(r===5)throw new pe("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new pe("Invalid JWT");if(!t)throw new pe("JWTs must contain a payload");let n;try{n=bi(t)}catch{throw new pe("Failed to parse the base64url encoded payload")}let i;try{i=JSON.parse(ue.decode(n))}catch{throw new pe("Failed to parse the decoded payload as JSON")}if(!Q(i))throw new pe("Invalid JWT Claims Set");return i}var Fm=I(()=>{gs();_e();$e();V();o(Hm,"decodeJwt")});async function qm(e,t){var r;let n,i,s;switch(e){case"HS256":case"HS384":case"HS512":n=parseInt(e.slice(-3),10),i={name:"HMAC",hash:`SHA-${n}`,length:n},s=["sign","verify"];break;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return n=parseInt(e.slice(-3),10),nr(new Uint8Array(n>>3));case"A128KW":case"A192KW":case"A256KW":n=parseInt(e.slice(1,4),10),i={name:"AES-KW",length:n},s=["wrapKey","unwrapKey"];break;case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":n=parseInt(e.slice(1,4),10),i={name:"AES-GCM",length:n},s=["encrypt","decrypt"];break;default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return U.subtle.generateKey(i,(r=t?.extractable)!==null&&r!==void 0?r:!1,s)}function Ml(e){var t;let r=(t=e?.modulusLength)!==null&&t!==void 0?t:2048;if(typeof r!="number"||r<2048)throw new k("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return r}async function $m(e,t){var r,n,i;let s,a;switch(e){case"PS256":case"PS384":case"PS512":s={name:"RSA-PSS",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ml(t)},a=["sign","verify"];break;case"RS256":case"RS384":case"RS512":s={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${e.slice(-3)}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ml(t)},a=["sign","verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":s={name:"RSA-OAEP",hash:`SHA-${parseInt(e.slice(-3),10)||1}`,publicExponent:new Uint8Array([1,0,1]),modulusLength:Ml(t)},a=["decrypt","unwrapKey","encrypt","wrapKey"];break;case"ES256":s={name:"ECDSA",namedCurve:"P-256"},a=["sign","verify"];break;case"ES384":s={name:"ECDSA",namedCurve:"P-384"},a=["sign","verify"];break;case"ES512":s={name:"ECDSA",namedCurve:"P-521"},a=["sign","verify"];break;case"EdDSA":a=["sign","verify"];let c=(r=t?.crv)!==null&&r!==void 0?r:"Ed25519";switch(c){case"Ed25519":case"Ed448":s={name:c};break;default:throw new k("Invalid or unsupported crv option provided")}break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{a=["deriveKey","deriveBits"];let u=(n=t?.crv)!==null&&n!==void 0?n:"P-256";switch(u){case"P-256":case"P-384":case"P-521":{s={name:"ECDH",namedCurve:u};break}case"X25519":case"X448":s={name:u};break;default:throw new k("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}break}default:throw new k('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return U.subtle.generateKey(s,(i=t?.extractable)!==null&&i!==void 0?i:!1,a)}var kl=I(()=>{Ie();V();si();o(qm,"generateSecret");o(Ml,"getModulusLengthOption");o($m,"generateKeyPair")});async function jm(e,t){return $m(e,t)}var Vm=I(()=>{kl();o(jm,"generateKeyPair")});async function Gm(e,t){return qm(e,t)}var Bm=I(()=>{kl();o(Gm,"generateSecret")});var bs={};Wi(bs,{CompactEncrypt:()=>pn,CompactSign:()=>hn,EmbeddedJWK:()=>Rm,EncryptJWT:()=>ms,FlattenedEncrypt:()=>Mt,FlattenedSign:()=>ur,GeneralEncrypt:()=>as,GeneralSign:()=>ps,SignJWT:()=>fs,UnsecuredJWT:()=>ys,base64url:()=>Ul,calculateJwkThumbprint:()=>xl,calculateJwkThumbprintUri:()=>Im,compactDecrypt:()=>ns,compactVerify:()=>us,createLocalJWKSet:()=>Nm,createRemoteJWKSet:()=>Lm,decodeJwt:()=>Hm,decodeProtectedHeader:()=>Mm,errors:()=>Xu,exportJWK:()=>is,exportPKCS8:()=>um,exportSPKI:()=>cm,flattenedDecrypt:()=>an,flattenedVerify:()=>cn,generalDecrypt:()=>im,generalVerify:()=>hm,generateKeyPair:()=>jm,generateSecret:()=>Gm,importJWK:()=>ar,importPKCS8:()=>Xf,importSPKI:()=>Yf,importX509:()=>Zf,jwtDecrypt:()=>bm,jwtVerify:()=>ym});var _s=I(()=>{bl();rs();om();lm();Il();cs();fm();gm();_m();Pl();ss();Ol();ds();vm();Tm();Sm();Am();Pm();Ll();Dm();Um();_l();di();km();Fm();V();Vm();Bm();gs()});var ws=g(Es=>{"use strict";Object.defineProperty(Es,"__esModule",{value:!0});Es.fetchRetry=void 0;var vS=D();async function TS(e,t,r){for(let n=0;n<=e.retries;n++){let i=fetch(t,r);if(n===e.retries)return i;let s=await i;if(s.status<500&&s.status!==429)return s;e?.logger?.error("Request failed, retrying",{method:typeof t=="string"?"GET":t.method,url:typeof t=="string"?t:t.url,status:s.status}),await new Promise(a=>setTimeout(a,e.retryDelayMs*Math.pow(2,n)))}throw new vS.ConfigurationError("An unknown error occurred, ensure retries is not negative")}o(TS,"fetchRetry");Es.fetchRetry=TS});var fn=g(et=>{"use strict";Object.defineProperty(et,"__esModule",{value:!0});et.GcpServiceAccount=et.fetchToken=et.exchangeGgpJwtForIdToken=et.exchangeFirebaseJwtForIdToken=et.getTokenFromGcpServiceAccount=void 0;var Km=(_s(),Qi(bs)),SS=D(),IS=ws();async function AS({serviceAccount:e,audience:t,expirationTime:r="1h",payload:n={}}){let{clientEmail:i,privateKeyId:s,privateKey:a}=e;return await new Km.SignJWT(n).setProtectedHeader({alg:"RS256",kid:s}).setIssuer(i).setSubject(i).setAudience(t).setIssuedAt().setExpirationTime(r).sign(a)}o(AS,"getTokenFromGcpServiceAccount");et.getTokenFromGcpServiceAccount=AS;async function RS(e,t,r){return Fl(e,{token:t,returnSecureToken:!0},r)}o(RS,"exchangeFirebaseJwtForIdToken");et.exchangeFirebaseJwtForIdToken=RS;async function PS(e,t,r){return Fl(e,{grant_type:"urn:ietf:params:oauth:grant-type:jwt-bearer",assertion:t},r)}o(PS,"exchangeGgpJwtForIdToken");et.exchangeGgpJwtForIdToken=PS;async function Fl(e,t,r){let n=await(0,IS.fetchRetry)(r,e,{method:"POST",headers:{"Content-Type":"application/json"},redirect:"follow",body:JSON.stringify(t)});if(n.status!==200){let s;try{let a=await n.text(),c=JSON.parse(a);s={cause:c.error??c}}catch{}throw new SS.RuntimeError({message:"Could not get token from Google Identity",extensionMembers:s})}return await n.json()}o(Fl,"fetchToken");et.fetchToken=Fl;var Hl=class e{static{o(this,"GcpServiceAccount")}#e;#t;constructor({serviceAccount:t,privateKey:r}){this.#t=t,this.#e=r}static async init(t){let r=JSON.parse(t),n=await(0,Km.importPKCS8)(r.private_key.trim(),"RS256");return new e({serviceAccount:r,privateKey:n})}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}};et.GcpServiceAccount=Hl});var Ts=g(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.GoogleLogTransport=kt.ZuploToGCPMap=kt.GoogleCloudLoggingPlugin=void 0;var OS=Se(),ql=ee(),$l=fn(),NS=Dt(),Jm=gt(),jl=class extends NS.LogPlugin{static{o(this,"GoogleCloudLoggingPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new vs(this.options)}};kt.GoogleCloudLoggingPlugin=jl;var xS="https://logging.googleapis.com/v2/entries:write?alt=json";kt.ZuploToGCPMap={error:"ERROR",warn:"WARNING",info:"INFO",debug:"DEBUG"};var vs=class{static{o(this,"GoogleLogTransport")}constructor(t){this.#r=t.logName,this.#e=t.serviceAccountJson,this.#i=ql.Environment.instance.loggingEnvironmentType,this.#o=ql.Environment.instance.loggingEnvironmentStage,this.#n=ql.Environment.instance.deploymentName}#e;#t;#r;#n;#i;#o;async log(t,r){if(t.messages.length===0)return;let n={allMessages:(0,Jm.makeErrorsSerializable)(t.messages)};this.#t||(this.#t=await $l.GcpServiceAccount.init(this.#e));let i=this.#t.projectId??"zuplo-production",s={logName:this.#r,resource:{type:"global"},severity:kt.ZuploToGCPMap[t.level],timestamp:t.timestamp,trace:`projects/${i}/traces/${t.requestId}`,labels:{requestId:t.requestId,buildId:t.buildId,source:t.logSource,loggingId:t.loggingId,logOwner:t.logOwner,environment:this.#n,environmentType:this.#i,environmentStage:this.#o}};t.rayId&&(s.labels.rayId=t.rayId);let a=(0,Jm.extractBestMessage)(n.allMessages);s.jsonPayload={...n,message:a},this.batcher.enqueue(s),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async t=>{if(t.length===0)return;this.#t||(this.#t=await $l.GcpServiceAccount.init(this.#e));let r=await(0,$l.getTokenFromGcpServiceAccount)({serviceAccount:this.#t,audience:"https://logging.googleapis.com/google.logging.v2.LoggingServiceV2"}),n=await fetch(xS,{method:"POST",body:JSON.stringify({entries:t}),headers:{Authorization:`Bearer ${r}`,"content-type":"application/json;charset=UTF-8"}});n.ok||console.error(n.status,n.statusText,await n.text())};batcher=new OS.BatchDispatch("google-log-transport",1,this.dispatchFunction)};kt.GoogleLogTransport=vs});var Vl=g(mn=>{"use strict";Object.defineProperty(mn,"__esModule",{value:!0});mn.gcpLogFormat=mn.GCP_LOG_FORMAT=void 0;var zm=gt(),CS=Ts();mn.GCP_LOG_FORMAT="gcp";function LS(e){let t={allMessages:(0,zm.makeErrorsSerializable)(e.messages)},r="zuplo-production",n=(0,zm.extractBestMessage)(t.allMessages),i={logName:`projects/${r}/logs/runtime-user`,message:n,severity:CS.ZuploToGCPMap[e.level],timestamp:e.timestamp,"logging.googleapis.com/labels":{buildId:e.buildId,source:e.logSource,loggingId:e.loggingId,logOwner:e.logOwner},"logging.googleapis.com/trace":`projects/${r}/traces/${e.requestId}`,allMessages:t.allMessages};return e.rayId&&(i["logging.googleapis.com/labels"].rayId=e.rayId),i}o(LS,"gcpLogFormat");mn.gcpLogFormat=LS});var Qm=g(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.ConsoleTransport=void 0;var Wm=Vl(),Gl=class{static{o(this,"ConsoleTransport")}constructor(t,r){this.#e=t??console,this.#t=r}#e;#t;async log(t){if(this.#t===Wm.GCP_LOG_FORMAT){if(t.messages.length===0)return;this.#e[t.level].apply(null,[(0,Wm.gcpLogFormat)(t)])}else this.#e[t.level].apply(null,[...t.messages,{logOwner:t.logOwner,logSource:t.logSource,level:t.level,timestamp:t.timestamp,loggingId:t.loggingId,rayId:t.rayId,requestId:t.requestId,buildId:t.buildId}])}};Ss.ConsoleTransport=Gl});var Ql=g(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.DataDogTransport=yn.DataDogLoggingPlugin=void 0;var DS=Se(),Bl=ee(),US=Dt(),Ym=gt(),Wl=class extends US.LogPlugin{static{o(this,"DataDogLoggingPlugin")}options;constructor(t){super(),this.options=t}getTransport(){return new Is(this.options)}};yn.DataDogLoggingPlugin=Wl;var Kl="__ddtags",Jl="__ddattr",zl=o(e=>e.replaceAll(",","_").replaceAll(":","_"),"cleanTagText"),MS=o(e=>{let t=Object.keys(e),r=[];return t.forEach(n=>{let i=e[n];i==null?r.push(zl(n)):r.push(`${zl(n)}:${zl(i.toString())}`)}),r.join(",")},"formatTags"),Is=class{static{o(this,"DataDogTransport")}constructor(t){this.#e=t.apiKey,this.#t=t.url??"https://http-intake.logs.datadoghq.com/api/v2/logs",this.#n=Bl.Environment.instance.loggingEnvironmentType,this.#i=Bl.Environment.instance.loggingEnvironmentStage,this.#r=Bl.Environment.instance.deploymentName}#e;#t;#r;#n;#i;async log(t,r){let n={},i=r.custom[Kl];i&&typeof i=="object"&&Object.assign(n,i);let s=[...t.messages],a=t.messages.findIndex(h=>h[Kl]!==void 0);a>-1&&(Object.assign(n,s[a][Kl]),s.splice(a,1));let c={},u=r.custom[Jl];u&&typeof u=="object"&&Object.assign(c,u);let l=t.messages.findIndex(h=>h[Jl]!==void 0);l>-1&&(Object.assign(c,s[l][Jl]),s.splice(l,1));let d=(0,Ym.makeErrorsSerializable)(s),y={message:{...{...t,activityId:t.requestId,trace:t.requestId},messages:d},ddsource:"Zuplo",hostname:new URL(r.originalRequest.url).hostname,msg:(0,Ym.extractBestMessage)(d),service:t.loggingId,ddtags:MS(n),environment:this.#r,environment_type:this.#n,environment_stage:this.#i};Object.assign(y,c),this.batcher.enqueue(y),r.waitUntil(this.batcher.waitUntilFlushed())}dispatchFunction=async t=>{t.length!==0&&await fetch(this.#t,{method:"POST",body:JSON.stringify([...t]),headers:{"content-type":"application/json","DD-API-KEY":this.#e}})};batcher=new DS.BatchDispatch("data-dog-transport",10,this.dispatchFunction)};yn.DataDogTransport=Is});var Xm=g(As=>{"use strict";Object.defineProperty(As,"__esModule",{value:!0});As.ProcessTransport=void 0;var Zm=Vl(),Yl=class{static{o(this,"ProcessTransport")}constructor(t,r){this.#e=t,this.#t=r}#e;#t;async log(t){if(this.#t===Zm.GCP_LOG_FORMAT){if(t.messages.length===0)return;this.#e[t.level].apply(null,[(0,Zm.gcpLogFormat)(t)])}else this.#e[t.level].apply(null,[...t.messages,{logOwner:t.logOwner,logSource:t.logSource,timestamp:t.timestamp,loggingId:t.loggingId,rayId:t.rayId,requestId:t.requestId,buildId:t.buildId,vectorClock:t.vectorClock}])}};As.ProcessTransport=Yl});var ty=g(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});Ps.RemoteLogTransport=void 0;var kS=Se(),ey=ee(),HS=gt(),FS=o(({url:e,remoteLogToken:t,loggingId:r,sendOnlyErrors:n})=>async i=>{let s;n===!0?s=i.filter(a=>a.level==="error"):s=i,s.length!==0&&fetch(`${e}/publish/${r}`,{method:"POST",body:JSON.stringify({timestamp:Date.now(),type:"log",message:s.map(a=>({...a,messages:(0,HS.makeErrorsSerializable)(a.messages)}))}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":ey.Environment.instance.systemUserAgent,"zp-dn":ey.Environment.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),Rs,Zl=class{static{o(this,"RemoteLogTransport")}constructor(t){Rs||(Rs=new kS.BatchDispatch("remote-log-transport",1,FS(t)))}async log(t,r){Rs.enqueue(t),r.waitUntil(Rs.waitUntilFlushed())}};Ps.RemoteLogTransport=Zl});var ry=g(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.unifiedFormatter=Ur.SeverityNumberOpenTelemetryMap=void 0;Ur.SeverityNumberOpenTelemetryMap={internal:1,trace:2,debug:5,info:9,warn:13,error:17,fatal:21};var qS=o((e,t)=>r=>{let n={};return n.deploymentName=e,n.labels={requestId:r.requestId,source:r.logSource,loggingId:r.loggingId,logOwner:r.logOwner},n.rayId=r.rayId??"",n.runtime={buildId:t.BUILD_ID,buildTimestamp:t.TIMESTAMP,gitSHA:t.GIT_SHA,version:t.ZUPLO_VERSION},n.atomicCounter=r.vectorClock,{timestamp:r.timestamp,observerdTimestamp:r.timestamp,traceId:r.requestId,severityText:r.level,severityNumber:Ur.SeverityNumberOpenTelemetryMap[r.level],body:r.messages,attributes:n}},"unifiedFormatter");Ur.unifiedFormatter=qS});var iy=g(Ns=>{"use strict";Object.defineProperty(Ns,"__esModule",{value:!0});Ns.UnifiedLogTransport=void 0;var $S=Se(),ny=ee(),jS=ry(),VS=o(({url:e,remoteLogToken:t,deploymentName:r,build:n})=>async i=>{if(i.length===0)return;let s=(0,jS.unifiedFormatter)(r,n);fetch(`${e}/v1/runtime-logs`,{method:"POST",body:JSON.stringify({entries:i.map(s)}),headers:{"content-type":"application/json",authentication:`Bearer ${t}`,"user-agent":ny.Environment.instance.systemUserAgent,"zp-dn":ny.Environment.instance.deploymentName??"unknown"}}).catch(a=>{console.error(a)})},"dispatchFunction"),Os,Xl=class{static{o(this,"UnifiedLogTransport")}constructor(t){Os||(Os=new $S.BatchDispatch("unified-log-transport",1,VS(t)))}async log(t,r){Os.enqueue(t),r.waitUntil(Os.waitUntilFlushed())}};Ns.UnifiedLogTransport=Xl});var dy=g(xs=>{"use strict";Object.defineProperty(xs,"__esModule",{value:!0});xs.LogInitializer=void 0;var GS=Sr(),BS=xt(),oy=Fu(),sy=ee(),ay=uf(),KS=Dt(),JS=lf(),cy=df(),uy=Qm(),zS=Ql(),WS=Ts(),ly=Xm(),QS=ty(),YS=iy(),ed=(0,GS.debug)("zuplo:logging"),td=class{static{o(this,"LogInitializer")}serviceProvider;systemCoreLogger;userCoreLogger;constructor(t){this.serviceProvider=t,this.systemCoreLogger=this.setupSystemCoreLogger(sy.Environment.instance),this.userCoreLogger=this.setupUserCoreLogger(sy.Environment.instance)}setupSystemCoreLogger(t){let{build:r}=t;ed("Gateway.setupSystemCoreLogger");let n=[],i=this.serviceProvider.getService(oy.SYSTEM_LOGGER);return i?n.push(new ly.ProcessTransport(i.logger,t.logFormat)):t.isDeno&&n.push(new uy.ConsoleTransport(console,t.logFormat)),t.isCloudflare&&t.deploymentName&&t.remoteLogToken&&n.push(new YS.UnifiedLogTransport({url:t.remoteLogURL,deploymentName:t.deploymentName,remoteLogToken:t.remoteLogToken,build:t.build})),new ay.CoreLogger(t.systemLogLevel,"system",t.loggingId,r.BUILD_ID,n)}setupUserCoreLogger(t){ed("Gateway.setupUserCoreLogger");let r=[],{runtime:n,build:i}=t,s=this.serviceProvider.getService(oy.SYSTEM_LOGGER);if(s&&s.captureUserLogs===!0?r.push(new ly.ProcessTransport(s.logger,t.logFormat)):t.isDeno&&r.push(new uy.ConsoleTransport(console,t.logFormat)),t.remoteLogToken&&t.loggingId&&r.push(new QS.RemoteLogTransport({loggingId:t.loggingId,url:t.remoteLogURL,remoteLogToken:t.remoteLogToken,sendOnlyErrors:t.isCloudflare})),n.GCP_USER_LOG_NAME&&n.GCP_USER_LOG_SVC_ACCT_JSON&&r.push(new WS.GoogleLogTransport({serviceAccountJson:n.GCP_USER_LOG_SVC_ACCT_JSON,logName:n.GCP_USER_LOG_NAME})),n.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY){let a=n.ZUPLO_USER_LOGGER_DATA_DOG_URL;r.push(new zS.DataDogTransport({apiKey:n.ZUPLO_USER_LOGGER_DATA_DOG_API_KEY,url:a}))}return BS.plugins.forEach(a=>{a instanceof KS.LogPlugin&&r.push(a.getTransport())}),new ay.CoreLogger(t.userLogLevel,"user",t.loggingId,i.BUILD_ID,r)}createRequestLoggers(t,r,n,i,s){ed("Gateway.createRequestLoggers");let a=new JS.LoggingContext(n,i,s),c=new cy.RequestLogger(t,r,this.systemCoreLogger,a);return{userRequestLogger:new cy.RequestLogger(t,r,this.userCoreLogger,a),systemRequestLogger:c}}};xs.LogInitializer=td});var nd=g(Cs=>{"use strict";Object.defineProperty(Cs,"__esModule",{value:!0});Cs.UserRouteConfiguration=void 0;var rd=class{static{o(this,"UserRouteConfiguration")}constructor(t){this.path=t.path,this.methods=t.methods,this.label=t.label,this.key=t.key,this.handler=t.handler,this.corsPolicy=t.corsPolicy,this.custom=t.custom,this.version=t.version,this.policies=t.policies,this.excludeFromOpenApi=t.excludeFromOpenApi,this.pathPattern=t.pathPattern,t.raw?(this.#e=t.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=t.operationId,this.summary=t.summary,this.tags=t.tags,this.parameters=t.parameters,this.responses=t.responses)}raw(){return this.#e}#e;label;key;path;summary;operationId;tags;parameters;responses;excludeFromOpenApi;pathPattern;custom;methods;handler;corsPolicy;version;policies};Cs.UserRouteConfiguration=rd});var od=g(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.Router=wt.RouterError=wt.LookupResult=wt.RouterEntry=void 0;var py=D(),ZS=mt(),XS=nd(),Ls=class{static{o(this,"RouterEntry")}constructor(t,r,n,i){this.fullPath=t,this.urlPattern=r,this.config=n,this.executableHandler=i}fullPath;urlPattern;config;executableHandler};wt.RouterEntry=Ls;var _i=class{static{o(this,"LookupResult")}constructor(t,r,n){this.routeConfiguration=t,this.params=n??{},this.executableHandler=r}executableHandler;routeConfiguration;params};wt.LookupResult=_i;var Ds=class extends Error{static{o(this,"RouterError")}constructor(t,r){super(t,r)}};wt.RouterError=Ds;var id=class{static{o(this,"Router")}constructor(t){this.routeEntries=[],this.versions=t}versions;routeEntries;addRoute(t,r){if(!(t instanceof XS.UserRouteConfiguration||t instanceof ZS.SystemRouteConfiguration))throw new py.SystemError("Config must be a UserRouteConfiguration or SystemRouteConfiguration");let n=this.versions.find(s=>s.name===t.version)?.pathPrefix,i;"pathPattern"in t&&t.pathPattern?i=`${n??""}${t.pathPattern}`:i=`${n??""}${t.path}`;try{let s=new URLPattern({pathname:i}),a=new Ls(i,s,t,r);Object.freeze(a.config),this.routeEntries.push(a)}catch(s){throw new Ds(`addRoute-error: Invalid path '${i}'. '${s.message}'`,{cause:s})}}lookup(t,r){if(typeof t>"u")throw new py.ConfigurationError(`Invalid request - Method was undefined. Path: '${r}'`);let n=this.routeEntries.filter(i=>i.config.methods.includes(t));if(n.length!==0)for(let i=0;i<n.length;i++){let s=n[i],c=s.urlPattern.exec({pathname:r});if(c!==null)return new _i(s.config,s.executableHandler,c.pathname.groups)}}lookupByPathOnly(t){let r=[];for(let n=0;n<this.routeEntries.length;n++){let i=this.routeEntries[n],a=i.urlPattern.exec({pathname:t});if(a!==null){let c=new _i(i.config,i.executableHandler,a.pathname.groups);r.push(c)}}return r}};wt.Router=id});var Mr=g(Ms=>{"use strict";Object.defineProperty(Ms,"__esModule",{value:!0});Ms.Gateway=void 0;var eI=Sr(),hy=Uh(),fy=Vh(),tI=Gh(),my=Bh(),yy=Wh(),Ht=Zn(),Us=Ir(),gy=cf(),Tt=D(),sd=xt(),rI=dy(),nI=Wt(),iI=le(),oI=Mu(),sI=Rr(),aI=ri(),cI=Je(),uI=od(),ad=mt(),by=nd(),lI=Ke(),dI=Ro(),_y=ee(),Ey=xr(),pI=["/__zuplo/ping","/__zuplo/open-api","/__zuplo/docs","/__zuplo/consumers","/__zuplo/external-users","/__zuplo/assets","/__zuplo/config","/__zuplo/build","/favicon.ico"],vt=(0,eI.debug)("zuplo:runtime"),hI=o(e=>{let t=e.findIndex(r=>r.name===ad.systemNoVersion.name);return t>-1?[...e.splice(t),ad.systemNoVersion]:[...e,ad.systemNoVersion]},"setupSystemNoVersion"),cd=class e{static{o(this,"Gateway")}routeData;runtimeSettings;schemaValidator;static#e;constructor(t,r,n,i){this.routeData=t,this.runtimeSettings=r,this.schemaValidator=i,vt("Gateway.constructor"),this.#r=this.setupRoutes(),this.#i=this.setupErrorHandler(),this.#t=new rI.LogInitializer(n)}static async initialize(t,r,n,i,s){if(vt("Gateway.initialize"),!e.#e){await(0,sd.initializeRuntime)(s);let a={...t,corsPolicies:(0,dI.parseCorsPolicies)(t.corsPolicies)},c=new e(a,r,n,i);e.#e=c}return e.#e}static purgeGatewayCache(){vt("Gateway.purgeGatewayCache"),e.#e=void 0}static get instance(){if(!e.#e)throw new Tt.SystemError("Gateway cannot be used before it is initialized");return e.#e}instanceId=crypto.randomUUID();#t;#r;#n=[aI.policyProcessor,oI.corsProcessor,sI.metricsProcessor];#i;setupRoutes=()=>{vt("Gateway.setupRoutes");let t=this.routeData,r=hI(t.versions),n=new uI.Router(r);if(t.routes.length===0)return(0,hy.registerBuildRoute)(n,this),(0,yy.registerPingRoute)(n,this),(0,fy.registerCorsRoute)(n,this),(0,tI.registerNoRoutes)(n,this),n;let{enabled:i}=this.runtimeSettings.developerPortal;return i&&((0,gy.registerDevPortalLegacyRedirectRoute)(n,this),(0,gy.registerDevPortalV3Route)(n,this)),(0,hy.registerBuildRoute)(n,this),(0,yy.registerPingRoute)(n,this),(0,fy.registerCorsRoute)(n,this),t.routes.forEach(s=>{let a;if(typeof s.handler?.module=="object"&&(a=s.handler?.module[s.handler.export]),typeof a!="function")throw new Tt.ConfigurationError(`Invalid state - No handler on route for path '${s.path}'`);let c=new nI.Pipeline({processors:this.#n,handler:a,gateway:this}),u=new by.UserRouteConfiguration(s);n.addRoute(u,c.execute)}),(0,my.registerNotMatchedHandler)(n,this),n};setupErrorHandler=()=>{let t;if(typeof this.routeData.requestErrorHandler?.module=="object"){if(t=this.routeData.requestErrorHandler.module[this.routeData.requestErrorHandler.export],typeof t!="function")throw new Tt.ConfigurationError("Invalid state - Module and export set for 'errorHandler' is not a function")}else t=o((r,n,i)=>this.#o(r,n,i),"errorHandler");return t};errorHandler(t,r,n){try{return this.#i(t,r,n)}catch(i){return vt("An error occurred in the user's errorHandler",i),this.#o(t,r,i)}}#o(t,r,n){vt("Gateway.internalErrorResponse");let i={};if(_y.Environment.instance.isDeno){if(n instanceof Tt.RuntimeError&&n.extensionMembers)i=n.extensionMembers;else if(n.cause){let s=(0,Ey.serializeError)(n.cause);"stack"in s&&(s.stack=(0,Ey.cleanStack)(s.stack)),i={cause:s}}}return iI.HttpProblems.internalServerError(t,r,{detail:n.message,...i})}#s(t){let r=new Headers(t.headers);return Ht.DISPATCH_HEADERS_TO_REMOVE.forEach(n=>{r.delete(n)}),_y.Environment.instance.isDeno&&Ht.INTERNAL_HEADERS_TO_REMOVE.forEach(n=>{r.delete(n)}),new Request(t,{headers:r})}async handleRequest(t,r){let n=t.headers.get(Ht.REQUEST_ID_HEADER)??t.headers.get(Ht.LEGACY_REQUEST_ID_HEADER),i=t.headers.get(Ht.RAY_ID_HEADER);if(!n){n=crypto.randomUUID();let T=new Headers(t.headers);T.set(Ht.REQUEST_ID_HEADER,n),t=new Request(t,{headers:T})}if(["GET","HEAD"].includes(t.method)&&t.body){let T=new Headers(t.headers);T.set(Ht.BODY_REMOVED_HEADER,"true"),t=new Request(t,{headers:T,body:null})}let s={},{userRequestLogger:a,systemRequestLogger:c}=this.#t.createRequestLoggers(n,i,r,s,t),u=new URL(t.url),l=u.pathname,d=this.#r.lookup(t.method,l);if(!d)throw new Tt.SystemError(`Invalid state - no route match - should have been picked up by the not found handler, path: '${l}'`);let p=new Us.HeaderIncomingRequestProperties(t.headers),y=this.#s(t),h=new cI.ZuploRequest(y,{params:d.params}),m=new Us.SystemZuploContext({logger:a,route:d.routeConfiguration,requestId:n,fetchEvent:r,custom:s,incomingRequestProperties:p}),v=Us.ZuploContextExtensions.initialize(m,h);if(d.routeConfiguration===my.notFoundRouteConfiguration&&sd.runtimeExtensions.value?.notFoundHandler!==void 0){let T=this.#r.lookupByPathOnly(l);v.pathOnlyMatches=T.map(S=>S.routeConfiguration).filter(S=>S instanceof by.UserRouteConfiguration)}try{if(lI.SystemLogMap.addLogger(m,c),!u.pathname.startsWith("/__zuplo")){let j=await(0,sd.invokeOnRequestExtensions)(h,m);if(j instanceof Response)return j;{let L=Us.ZuploContextExtensions.getContextExtensions(m);h=j,L.latestRequest=h}}[...pI,...this.runtimeSettings.developerPortal.enabled?[this.runtimeSettings.developerPortal.sitePathname]:[]].filter(j=>new RegExp(j).test(u.pathname)).length===0&&a.debug(`Request received '${u.pathname}'`,{method:t.method,url:u.pathname,hostname:u.hostname,route:d.routeConfiguration.path});let S=d.executableHandler;fI(S,d,t),vt("Gateway.handleRequest - call user handler");let O=await S(h,m);if(vt("Gateway.handleRequest - user handler"),!(O instanceof Response))throw new Tt.RuntimeError(`Invalid Response type from the request handler: ${typeof O}`);if(O.bodyUsed)throw new Tt.RuntimeError("The response object has already been used. Return a new response instead.");if(O.headers.get(Ht.REQUEST_ID_HEADER)===null&&!O.webSocket){let j=new Headers(O.headers);return j.set(Ht.REQUEST_ID_HEADER,n),new Response(O.body,{status:O.status,statusText:O.statusText,headers:j,cf:O.cf})}else return O}catch(T){return vt("Gateway - error executing handler",T),T instanceof Tt.RuntimeError?(a.error(T),c.warn(T)):c.error(T),await this.#o(h,m,T)}}};Ms.Gateway=cd;function fI(e,t,r){if(vt("Gateway.checkHandler"),!e)throw typeof t.routeConfiguration>"u"?new Tt.ConfigurationError(`Invalid state - no routeConfiguration for '${r.method}:${r.url}`):new Tt.ConfigurationError(`Invalid state. No handler for request '${r.method}':'${t.routeConfiguration.path}'`)}o(fI,"checkHandler")});var wy=g(ks=>{"use strict";Object.defineProperty(ks,"__esModule",{value:!0});ks.invokeInboundPolicy=void 0;var mI=D(),yI=Mr(),gI=ri(),bI=o(async(e,t,r)=>{let n=yI.Gateway.instance.routeData.policies,i=(0,gI.getInboundPolicyHandlerAndOptions)([e],n);if(i.length===0)throw new mI.RuntimeError(`Invalid 'invokeInboundPolicy call' - no policy '${e}' found.`);let s=i[0];return s.handler(t,r,s.options,e)},"invokeInboundPolicy");ks.invokeInboundPolicy=bI});var Ir=g(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.SystemZuploContext=tt.ZuploContextExtensions=tt.ResponseSentEvent=tt.ResponseSendingEvent=tt.HeaderIncomingRequestProperties=void 0;var we=Zn(),_I=D(),EI=wy(),ud=class{static{o(this,"HeaderIncomingRequestProperties")}#e;constructor(t){this.#e=t}get asn(){try{let t=this.#e.get(we.ZP_ASN_HEADER);if(typeof t=="string")return parseInt(t)}catch{}}get asOrganization(){return this.#e.get(we.ZP_AS_ORG_HEADER)??void 0}get city(){return this.#e.get(we.CF_IP_CITY_HEADER)??this.#e.get(we.ZP_IP_CITY_HEADER)??void 0}get continent(){return this.#e.get(we.CF_IP_CONTINENT_HEADER)??this.#e.get(we.ZP_IP_CONTINENT_HEADER)??void 0}get country(){return this.#e.get(we.CF_IP_COUNTRY_HEADER)??this.#e.get(we.ZP_IP_COUNTRY_HEADER)??void 0}get latitude(){return this.#e.get(we.CF_IP_LATITUDE_HEADER)??this.#e.get(we.ZP_IP_LATITUDE_HEADER)??void 0}get longitude(){return this.#e.get(we.CF_IP_LONGITUDE_HEADER)??this.#e.get(we.ZP_IP_LONGITUDE_HEADER)??void 0}get colo(){return this.#e.get(we.ZP_COLO_HEADER)??void 0}get postalCode(){return this.#e.get(we.ZP_POSTAL_CODE_HEADER)??void 0}get metroCode(){return this.#e.get(we.ZP_METRO_CODE_HEADER)??void 0}get region(){return this.#e.get(we.ZP_REGION_HEADER)??void 0}get regionCode(){return this.#e.get(we.ZP_REGION_CODE_HEADER)??void 0}get timezone(){return this.#e.get(we.ZP_TIMEZONE_HEADER)??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}}};tt.HeaderIncomingRequestProperties=ud;var ld=class extends Event{static{o(this,"ResponseSendingEvent")}constructor(t,r){super("responseSending"),this.request=t,this.mutableResponse=r}request;mutableResponse};tt.ResponseSendingEvent=ld;var dd=class extends Event{static{o(this,"ResponseSentEvent")}constructor(t,r){super("responseSent"),this.request=t,this.response=r}request;response};tt.ResponseSentEvent=dd;var Ei=class e{static{o(this,"ZuploContextExtensions")}static#e=new WeakMap;static initialize(t,r){if(!e.#e.has(t)){let n=new e(r);return e.#e.set(t,n),n}throw new Error(`ZuploContextExtensions already initialized for context with requestId '${t.requestId}'`)}static getContextExtensions(t){let r=e.#e.get(t);if(!r)throw new _I.RuntimeError(`Invalid state, could not get ZuploContext extensions for context with requestId '${t.requestId}'`);return r}latestRequest;pathOnlyMatches;#t;#r;constructor(t){this.latestRequest=t,this.#t=[],this.#r=[]}addResponseSendingHook(t){this.#r.push(t)}addResponseSendingFinalHook(t){this.#t.push(t)}onResponseSendingFinal=async(t,r,n)=>{for(let i of this.#t)await i(t,r,n)};onResponseSending=async(t,r,n)=>{let i=t;for(let s of this.#r)i=await s(t,r,n);return i}};tt.ZuploContextExtensions=Ei;var pd=class extends EventTarget{static{o(this,"SystemZuploContext")}constructor({logger:t,route:r,requestId:n,fetchEvent:i,custom:s,incomingRequestProperties:a}){super(),this.log=Object.freeze(t),this.route=r,this.requestId=n,this.custom=s,this.incomingRequestProperties=a,this.#e=i,this.invokeInboundPolicy=(c,u)=>(0,EI.invokeInboundPolicy)(c,u,this),this.waitUntil=c=>{this.#e.waitUntil(c)},this.addResponseSendingHook=c=>{Ei.getContextExtensions(this).addResponseSendingHook(c)},this.addResponseSendingFinalHook=c=>{Ei.getContextExtensions(this).addResponseSendingFinalHook(c)},Object.freeze(this)}#e;requestId;log;route;custom;incomingRequestProperties;invokeInboundPolicy;waitUntil;addResponseSendingHook;addResponseSendingFinalHook;addEventListener(t,r,n){let i=o(s=>{try{typeof r=="function"?r(s):r.handleEvent(s)}catch(a){throw this.log.error(`Error invoking event ${t}. See following logs for details.`),a}},"wrapped");super.addEventListener(t,i,n)}};tt.SystemZuploContext=pd});var vy=g(Hs=>{"use strict";Object.defineProperty(Hs,"__esModule",{value:!0});Hs.ContextData=void 0;var hd=class e{static{o(this,"ContextData")}static#e;#t;constructor(t){this.#t=t}set(t,r){e.set(t,this.#t,r)}get(t){return e.get(t,this.#t)}static set(t,r,n){e.#e||(e.#e=new WeakMap);let i=e.#e.get(t);i||(i=new Map),i.set(r,n),e.#e.set(t,i)}static get(t,r){return e.#e||(e.#e=new WeakMap),e.#e.get(t)?.get(r)}};Hs.ContextData=hd});var fd=g(pr=>{"use strict";Object.defineProperty(pr,"__esModule",{value:!0});pr.environment=pr.isZuploReadableEnvVariableName=pr.isRestrictedEnvVariableName=void 0;var wI=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function Ty(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!wI.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}o(Ty,"isRestrictedEnvVariableName");pr.isRestrictedEnvVariableName=Ty;function Sy(e){return!!e.startsWith("ZUPLO_")}o(Sy,"isZuploReadableEnvVariableName");pr.isZuploReadableEnvVariableName=Sy;var vI=new Proxy({},{get(e,t){if(Ty(String(t))&&!Sy(String(t)))return;let r=globalThis,n;return r.process?n=r.process.env[t]:n=r[t],n}});pr.environment=vI});var md=g(gn=>{"use strict";Object.defineProperty(gn,"__esModule",{value:!0});gn.externalServiceHandler=gn.externalServiceTunnelConfig=void 0;var TI=Sr(),kr=D(),SI=yd(),wi=ee(),ct=(0,TI.debug)("zuplo:runtime:external-service");function Ay(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=wi.Environment.instance.runtime;if(t&&t!=="undefined")try{let r=atob(t);e=JSON.parse(r)}catch{}return e}o(Ay,"getServiceAuth");async function II(e){let t=Ay();if(!t)throw ct("There is no external service auth configured for this zup."),new kr.RuntimeError("There are no external services configured for this zup.");if(typeof e!="string")throw ct("Cannot call external service with Request object"),new kr.RuntimeError("Currently, we only support fetch(<some_string>, ...).");let n=new URL(e).hostname,i={};i["CF-Access-Client-Id"]=t.clientId,i["CF-Access-Client-Secret"]=t.clientSecret;let s;if(t.customServiceMapping&&t.customServiceMapping[n])s=`https://${t.customServiceMapping[n]}`;else if(wi.Environment.instance.useSha256ServiceRouting){ct("Using sha256 service routing");let a=wi.Environment.instance.build;if(a.ACCOUNT_NAME&&a.PROJECT_NAME&&a.ENVIRONMENT_TYPE)s=`https://${await Ry(n,a.ACCOUNT_NAME,a.PROJECT_NAME,a.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ct("Cannot use sha256 service routing, missing build variables"),new kr.RuntimeError("Failed to generate fully qualified tunnel url.")}else s=`https://${n}.zuptunnel.com`;return{serviceBaseUrl:s,tunnelHeaders:i}}o(II,"externalServiceTunnelConfig");gn.externalServiceTunnelConfig=II;async function AI(e,t){let r=Ay();if(r)if(ct(`Using external service auth. ClientId: ${r.clientId})`),typeof e=="string"){let n=new URL(e),i=n.hostname,s=t??{},a=new Headers(s.headers||{});a.set("CF-Access-Client-Id",r.clientId),a.set("CF-Access-Client-Secret",r.clientSecret),s.headers=a;let c;if(r.customServiceMapping&&r.customServiceMapping[i])c=`https://${r.customServiceMapping[i]}`;else if(wi.Environment.instance.useSha256ServiceRouting){ct("Using sha256 service routing");let d=wi.Environment.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)c=`https://${await Ry(i,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw ct("Cannot use sha256 service routing, missing build variables"),new kr.RuntimeError("Failed to generate fully qualified tunnel url.")}else c=`https://${i}.zuptunnel.com`;let u=new URL(`${c}${n.pathname}${n.search}`);ct(`Calling external service: ${u.toString()}`);let l=await(0,SI.originalFetch)(u.toString(),s);if(l.status===403&&l.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:r.clientId,tunnelHost:c}),new kr.RuntimeError("Could not connect to secure tunnel.");return l}else throw ct("Cannot call external service with Request object"),new kr.RuntimeError("Currently, we only support fetch(<some_string>, ...).");else throw ct("There is no external service auth configured for this zup."),new kr.RuntimeError("There are no external services configured for this zup.")}o(AI,"externalServiceHandler");gn.externalServiceHandler=AI;async function Ry(e,t,r,n){let i=e.toLowerCase(),s=t.toLowerCase(),a=r.toLowerCase(),c=RI(n);ct(`Hashing service name: ${s}-${i}.${s}-${a}-${c}`);let u=await Iy(`${s}-${i}`),l=await Iy(`${s}-${a}-${c}`);return`${u}.${l}`}o(Ry,"hashServiceName");async function Iy(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(s=>s.toString(16).padStart(2,"0")).join("").slice(0,-1)}o(Iy,"hashSegment");function RI(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}o(RI,"sanitizeEnvironmentType")});var yd=g(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.originalFetch=void 0;var PI=md(),Py=new Map;Py.set("service:",PI.externalServiceHandler);bn.originalFetch=globalThis.fetch;globalThis.fetch=function(e,t){let r=OI(t);if(typeof e=="string"){let n=new URL(e),i=Py.get(n.protocol);return i?i(e,r):(0,bn.originalFetch)(e,r)}else return(0,bn.originalFetch)(e,r)};var OI=o(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let r=e;return r.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit")});var xy=g(_n=>{"use strict";Object.defineProperty(_n,"__esModule",{value:!0});_n.Handler=_n.purgeGatewayCache=void 0;var NI=D(),Ny=Mr(),Oy=ee(),xI=o(()=>{Ny.Gateway.purgeGatewayCache()},"purgeGatewayCache");_n.purgeGatewayCache=xI;var gd=class{static{o(this,"Handler")}routeData;buildEnvironment;runtimeEnvironment;runtimeSettings;serviceProvider;schemaValidations;runtimeInit;constructor(t,r,n,i,s,a,c){this.routeData=t,this.buildEnvironment=r,this.runtimeEnvironment=n,this.runtimeSettings=i,this.serviceProvider=s,this.schemaValidations=a,this.runtimeInit=c}requestHandler=async(t,r)=>{Oy.Environment.initialize(this.buildEnvironment,this.runtimeEnvironment);let n;try{n=await Ny.Gateway.initialize(this.routeData,this.runtimeSettings,this.serviceProvider,this.schemaValidations,this.runtimeInit)}catch(i){console.error("Error initializing gateway.",i);let s="Error initializing gateway. Check your 'zuplo.runtime.ts' for errors or contact support.";i instanceof NI.ConfigurationError&&(s=i.message);let a={status:500,title:"Gateway Initialization Error",type:"https://httpproblems.com/http-status/500",detail:s,instance:t.url,trace:{timestamp:Date.now(),rayId:t.headers.get("cf-ray")??void 0,buildId:this.buildEnvironment.BUILD_ID},message:Oy.Environment.instance.isDeno?i.message:void 0};return new Response(JSON.stringify(a,null,2),{status:500,headers:{"content-type":"application/json"}})}return n.handleRequest(t,r)}};_n.Handler=gd});var Uy=g(Ne=>{"use strict";Object.defineProperty(Ne,"__esModule",{value:!0});Ne.pathToRegexp=Ne.tokensToRegexp=Ne.regexpToFunction=Ne.match=Ne.tokensToFunction=Ne.compile=Ne.parse=void 0;function CI(e){for(var t=[],r=0;r<e.length;){var n=e[r];if(n==="*"||n==="+"||n==="?"){t.push({type:"MODIFIER",index:r,value:e[r++]});continue}if(n==="\\"){t.push({type:"ESCAPED_CHAR",index:r++,value:e[r++]});continue}if(n==="{"){t.push({type:"OPEN",index:r,value:e[r++]});continue}if(n==="}"){t.push({type:"CLOSE",index:r,value:e[r++]});continue}if(n===":"){for(var i="",s=r+1;s<e.length;){var a=e.charCodeAt(s);if(a>=48&&a<=57||a>=65&&a<=90||a>=97&&a<=122||a===95){i+=e[s++];continue}break}if(!i)throw new TypeError("Missing parameter name at ".concat(r));t.push({type:"NAME",index:r,value:i}),r=s;continue}if(n==="("){var c=1,u="",s=r+1;if(e[s]==="?")throw new TypeError('Pattern cannot start with "?" at '.concat(s));for(;s<e.length;){if(e[s]==="\\"){u+=e[s++]+e[s++];continue}if(e[s]===")"){if(c--,c===0){s++;break}}else if(e[s]==="("&&(c++,e[s+1]!=="?"))throw new TypeError("Capturing groups are not allowed at ".concat(s));u+=e[s++]}if(c)throw new TypeError("Unbalanced pattern at ".concat(r));if(!u)throw new TypeError("Missing pattern at ".concat(r));t.push({type:"PATTERN",index:r,value:u}),r=s;continue}t.push({type:"CHAR",index:r,value:e[r++]})}return t.push({type:"END",index:r,value:""}),t}o(CI,"lexer");function bd(e,t){t===void 0&&(t={});for(var r=CI(e),n=t.prefixes,i=n===void 0?"./":n,s="[^".concat(En(t.delimiter||"/#?"),"]+?"),a=[],c=0,u=0,l="",d=o(function(ie){if(u<r.length&&r[u].type===ie)return r[u++].value},"tryConsume"),p=o(function(ie){var ge=d(ie);if(ge!==void 0)return ge;var Be=r[u],E=Be.type,H=Be.index;throw new TypeError("Unexpected ".concat(E," at ").concat(H,", expected ").concat(ie))},"mustConsume"),y=o(function(){for(var ie="",ge;ge=d("CHAR")||d("ESCAPED_CHAR");)ie+=ge;return ie},"consumeText");u<r.length;){var h=d("CHAR"),m=d("NAME"),v=d("PATTERN");if(m||v){var T=h||"";i.indexOf(T)===-1&&(l+=T,T=""),l&&(a.push(l),l=""),a.push({name:m||c++,prefix:T,suffix:"",pattern:v||s,modifier:d("MODIFIER")||""});continue}var S=h||d("ESCAPED_CHAR");if(S){l+=S;continue}l&&(a.push(l),l="");var O=d("OPEN");if(O){var T=y(),j=d("NAME")||"",L=d("PATTERN")||"",ne=y();p("CLOSE"),a.push({name:j||(L?c++:""),pattern:j&&!L?s:L,prefix:T,suffix:ne,modifier:d("MODIFIER")||""});continue}p("END")}return a}o(bd,"parse");Ne.parse=bd;function LI(e,t){return Cy(bd(e,t),t)}o(LI,"compile");Ne.compile=LI;function Cy(e,t){t===void 0&&(t={});var r=_d(t),n=t.encode,i=n===void 0?function(u){return u}:n,s=t.validate,a=s===void 0?!0:s,c=e.map(function(u){if(typeof u=="object")return new RegExp("^(?:".concat(u.pattern,")$"),r)});return function(u){for(var l="",d=0;d<e.length;d++){var p=e[d];if(typeof p=="string"){l+=p;continue}var y=u?u[p.name]:void 0,h=p.modifier==="?"||p.modifier==="*",m=p.modifier==="*"||p.modifier==="+";if(Array.isArray(y)){if(!m)throw new TypeError('Expected "'.concat(p.name,'" to not repeat, but got an array'));if(y.length===0){if(h)continue;throw new TypeError('Expected "'.concat(p.name,'" to not be empty'))}for(var v=0;v<y.length;v++){var T=i(y[v],p);if(a&&!c[d].test(T))throw new TypeError('Expected all "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix}continue}if(typeof y=="string"||typeof y=="number"){var T=i(String(y),p);if(a&&!c[d].test(T))throw new TypeError('Expected "'.concat(p.name,'" to match "').concat(p.pattern,'", but got "').concat(T,'"'));l+=p.prefix+T+p.suffix;continue}if(!h){var S=m?"an array":"a string";throw new TypeError('Expected "'.concat(p.name,'" to be ').concat(S))}}return l}}o(Cy,"tokensToFunction");Ne.tokensToFunction=Cy;function DI(e,t){var r=[],n=Ed(e,r,t);return Ly(n,r,t)}o(DI,"match");Ne.match=DI;function Ly(e,t,r){r===void 0&&(r={});var n=r.decode,i=n===void 0?function(s){return s}:n;return function(s){var a=e.exec(s);if(!a)return!1;for(var c=a[0],u=a.index,l=Object.create(null),d=o(function(y){if(a[y]===void 0)return"continue";var h=t[y-1];h.modifier==="*"||h.modifier==="+"?l[h.name]=a[y].split(h.prefix+h.suffix).map(function(m){return i(m,h)}):l[h.name]=i(a[y],h)},"_loop_1"),p=1;p<a.length;p++)d(p);return{path:c,index:u,params:l}}}o(Ly,"regexpToFunction");Ne.regexpToFunction=Ly;function En(e){return e.replace(/([.+*?=^!:${}()[\]|/\\])/g,"\\$1")}o(En,"escapeString");function _d(e){return e&&e.sensitive?"":"i"}o(_d,"flags");function UI(e,t){if(!t)return e;for(var r=/\((?:\?<(.*?)>)?(?!\?)/g,n=0,i=r.exec(e.source);i;)t.push({name:i[1]||n++,prefix:"",suffix:"",modifier:"",pattern:""}),i=r.exec(e.source);return e}o(UI,"regexpToRegexp");function MI(e,t,r){var n=e.map(function(i){return Ed(i,t,r).source});return new RegExp("(?:".concat(n.join("|"),")"),_d(r))}o(MI,"arrayToRegexp");function kI(e,t,r){return Dy(bd(e,r),t,r)}o(kI,"stringToRegexp");function Dy(e,t,r){r===void 0&&(r={});for(var n=r.strict,i=n===void 0?!1:n,s=r.start,a=s===void 0?!0:s,c=r.end,u=c===void 0?!0:c,l=r.encode,d=l===void 0?function(H){return H}:l,p=r.delimiter,y=p===void 0?"/#?":p,h=r.endsWith,m=h===void 0?"":h,v="[".concat(En(m),"]|$"),T="[".concat(En(y),"]"),S=a?"^":"",O=0,j=e;O<j.length;O++){var L=j[O];if(typeof L=="string")S+=En(d(L));else{var ne=En(d(L.prefix)),ie=En(d(L.suffix));if(L.pattern)if(t&&t.push(L),ne||ie)if(L.modifier==="+"||L.modifier==="*"){var ge=L.modifier==="*"?"?":"";S+="(?:".concat(ne,"((?:").concat(L.pattern,")(?:").concat(ie).concat(ne,"(?:").concat(L.pattern,"))*)").concat(ie,")").concat(ge)}else S+="(?:".concat(ne,"(").concat(L.pattern,")").concat(ie,")").concat(L.modifier);else L.modifier==="+"||L.modifier==="*"?S+="((?:".concat(L.pattern,")").concat(L.modifier,")"):S+="(".concat(L.pattern,")").concat(L.modifier);else S+="(?:".concat(ne).concat(ie,")").concat(L.modifier)}}if(u)i||(S+="".concat(T,"?")),S+=r.endsWith?"(?=".concat(v,")"):"$";else{var Be=e[e.length-1],E=typeof Be=="string"?T.indexOf(Be[Be.length-1])>-1:Be===void 0;i||(S+="(?:".concat(T,"(?=").concat(v,"))?")),E||(S+="(?=".concat(T,"|").concat(v,")"))}return new RegExp(S,_d(r))}o(Dy,"tokensToRegexp");Ne.tokensToRegexp=Dy;function Ed(e,t,r){return e instanceof RegExp?UI(e,t):Array.isArray(e)?MI(e,t,r):kI(e,t,r)}o(Ed,"pathToRegexp");Ne.pathToRegexp=Ed});var Sd=g(wn=>{"use strict";Object.defineProperty(wn,"__esModule",{value:!0});wn.AwsV4Signer=wn.AwsClient=void 0;var HI=Sr(),Fy=D(),FI=(0,HI.debug)("zuplo:runtime"),vd=new TextEncoder,My={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"},qI=["authorization","content-type","content-length","user-agent","presigned-expires","expect","x-amzn-trace-id","range","connection"],Td=class{static{o(this,"AwsClient")}accessKeyId;secretAccessKey;sessionToken;service;region;cache;retries;initRetryMs;constructor({accessKeyId:t,secretAccessKey:r,sessionToken:n,service:i,region:s,cache:a,retries:c,initRetryMs:u}){if(t==null)throw new TypeError("accessKeyId is a required option");if(r==null)throw new TypeError("secretAccessKey is a required option");this.accessKeyId=t,this.secretAccessKey=r,this.sessionToken=n,this.service=i,this.region=s,this.cache=a||new Map,this.retries=c??0,this.initRetryMs=u||50}async sign(t,r){let n=new Fs(Object.assign({url:t},r,this,r&&r.aws)),i=Object.assign({},r,await n.sign());return delete i.aws,{url:i.url.toString(),request:i}}async fetch(t,r){FI("AWS fetch",t);for(let n=0;n<=this.retries;n++){let{url:i,request:s}=await this.sign(t,r),a=fetch(i,s);if(n===this.retries)return a;let c=await a;if(c.status<500&&c.status!==429)return c;await new Promise(u=>setTimeout(u,Math.random()*this.initRetryMs*Math.pow(2,n)))}throw new Fy.ConfigurationError("An unknown error occurred, ensure retries is not negative")}};wn.AwsClient=Td;var Fs=class{static{o(this,"AwsV4Signer")}method;url;headers;body;accessKeyId;secretAccessKey;sessionToken;service;region;cache;datetime;signQuery;appendSessionToken;signableHeaders;signedHeaders;canonicalHeaders;credentialString;encodedPath;encodedSearch;constructor({method:t,url:r,headers:n,body:i,accessKeyId:s,secretAccessKey:a,sessionToken:c,service:u,region:l,cache:d,datetime:p,signQuery:y,appendSessionToken:h,allHeaders:m,singleEncode:v}){if(r==null)throw new TypeError("url is a required option");if(s==null)throw new TypeError("accessKeyId is a required option");if(a==null)throw new TypeError("secretAccessKey is a required option");this.method=t||(i?"POST":"GET"),this.url=new URL(r),this.headers=new Headers(n||{}),this.body=i,this.accessKeyId=s,this.secretAccessKey=a,this.sessionToken=c;let T,S;(!u||!l)&&([T,S]=$I(this.url,this.headers)),this.service=u||T||"",this.region=l||S||"us-east-1",this.cache=d||new Map,this.datetime=p||new Date().toISOString().replace(/[:-]|\.\d{3}/g,""),this.signQuery=y,this.appendSessionToken=h||this.service==="iotdevicegateway",this.headers.delete("Host");let O=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"),O.set("X-Amz-Date",this.datetime),this.sessionToken&&!this.appendSessionToken&&O.set("X-Amz-Security-Token",this.sessionToken),this.signableHeaders=["host",...this.headers.keys()].filter(L=>m||!qI.includes(L)).sort(),this.signedHeaders=this.signableHeaders.join(";"),this.canonicalHeaders=this.signableHeaders.map(L=>L+":"+(L==="host"?this.url.host:(this.headers.get(L)||"").replace(/\s+/g," "))).join(`
60
60
  `),this.credentialString=[this.datetime.slice(0,8),this.region,this.service,"aws4_request"].join("/"),this.signQuery&&(this.service==="s3"&&!O.has("X-Amz-Expires")&&O.set("X-Amz-Expires","86400"),O.set("X-Amz-Algorithm","AWS4-HMAC-SHA256"),O.set("X-Amz-Credential",this.accessKeyId+"/"+this.credentialString),O.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,"/");v||(this.encodedPath=encodeURIComponent(this.encodedPath).replace(/%2F/g,"/")),this.encodedPath=Hy(this.encodedPath);let j=new Set;this.encodedSearch=[...this.url.searchParams].filter(([L])=>{if(!L)return!1;if(this.service==="s3"){if(j.has(L))return!1;j.add(L)}return!0}).map(L=>L.map(ne=>Hy(encodeURIComponent(ne)))).sort(([L,ne],[ie,ge])=>L<ie?-1:L>ie?1:ne<ge?-1:ne>ge?1:0).map(L=>L.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 t=this.datetime.slice(0,8),r=[this.secretAccessKey,t,this.region,this.service].join(),n=this.cache.get(r);if(!n){let i=await vi("AWS4"+this.secretAccessKey,t),s=await vi(i,this.region),a=await vi(s,this.service);n=await vi(a,"aws4_request"),this.cache.set(r,n)}return wd(await vi(n,await this.stringToSign()))}async stringToSign(){return["AWS4-HMAC-SHA256",this.datetime,this.credentialString,wd(await ky(await this.canonicalString()))].join(`
61
61
  `)}async canonicalString(){return[this.method.toUpperCase(),this.encodedPath,this.encodedSearch,this.canonicalHeaders+`
62
62
  `,this.signedHeaders,await this.hexBodyHash()].join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zuplo/graphql",
3
- "version": "5.1647.0",
3
+ "version": "5.1648.0",
4
4
  "repository": "https://github.com/zuplo/zuplo",
5
5
  "author": "Zuplo, Inc.",
6
6
  "exports": {