@zuplo/runtime 5.2383.0 → 5.2384.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/out/cjs/index.js +20 -20
- package/out/cjs/internal/index.js +1 -1
- package/out/cjs/policies/axiomatics-authz-inbound/exports.js +10 -10
- package/out/esm/{chunk-OBIMLM2A.js → chunk-BUNYKRVW.js} +2 -2
- package/out/esm/chunk-HAXIE4MQ.js +26 -0
- package/out/esm/{chunk-SLESBKUA.js → chunk-W2THI7KO.js} +2 -2
- package/out/esm/index.js +1 -1
- package/out/esm/internal/index.js +1 -1
- package/out/esm/policies/axiomatics-authz-inbound/exports.js +1 -1
- package/package.json +2 -1
- package/out/esm/chunk-7HJ5MMZB.js +0 -26
- /package/out/esm/{chunk-OBIMLM2A.js.LEGAL.txt → chunk-BUNYKRVW.js.LEGAL.txt} +0 -0
- /package/out/esm/{chunk-7HJ5MMZB.js.LEGAL.txt → chunk-HAXIE4MQ.js.LEGAL.txt} +0 -0
- /package/out/esm/{chunk-SLESBKUA.js.LEGAL.txt → chunk-W2THI7KO.js.LEGAL.txt} +0 -0
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
"use strict";var
|
|
25
|
+
"use strict";var U=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var x=Object.getOwnPropertyNames;var V=Object.prototype.hasOwnProperty;var i=(e,t)=>U(e,"name",{value:t,configurable:!0});var G=(e,t)=>{for(var n in t)U(e,n,{get:t[n],enumerable:!0})},k=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let l of x(t))!V.call(e,l)&&l!==n&&U(e,l,{get:()=>t[l],enumerable:!(o=w(t,l))||o.enumerable});return e};var B=e=>k(U({},"__esModule",{value:!0}),e);var H={};G(H,{getIdForParameterSchema:()=>D,getIdForRefSchema:()=>M,getIdForRequestBodySchema:()=>S,getRawOperationDataIdentifierName:()=>v,isRestrictedEnvVariableName:()=>R,isZuploReadableEnvVariableName:()=>T,sanitizedIdentifierName:()=>O});module.exports=B(H);function F(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let r=0;r<t.length;r++)t[r]=255;for(let r=0;r<e.length;r++){let s=e.charAt(r),d=s.charCodeAt(0);if(t[d]!==255)throw new TypeError(s+" is ambiguous");t[d]=r}let n=e.length,o=e.charAt(0),l=Math.log(n)/Math.log(256),E=Math.log(256)/Math.log(n);function L(r){if(r instanceof Uint8Array||(ArrayBuffer.isView(r)?r=new Uint8Array(r.buffer,r.byteOffset,r.byteLength):Array.isArray(r)&&(r=Uint8Array.from(r))),!(r instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(r.length===0)return"";let s=0,d=0,_=0,c=r.length;for(;_!==c&&r[_]===0;)_++,s++;let f=(c-_)*E+1>>>0,g=new Uint8Array(f);for(;_!==c;){let a=r[_],h=0;for(let m=f-1;(a!==0||h<d)&&m!==-1;m--,h++)a+=256*g[m]>>>0,g[m]=a%n>>>0,a=a/n>>>0;if(a!==0)throw new Error("Non-zero carry");d=h,_++}let p=f-d;for(;p!==f&&g[p]===0;)p++;let P=o.repeat(s);for(;p<f;++p)P+=e.charAt(g[p]);return P}i(L,"encode");function I(r){if(typeof r!="string")throw new TypeError("Expected String");if(r.length===0)return new Uint8Array;let s=0,d=0,_=0;for(;r[s]===o;)d++,s++;let c=(r.length-s)*l+1>>>0,f=new Uint8Array(c);for(;r[s];){let a=t[r.charCodeAt(s)];if(a===255)return;let h=0;for(let m=c-1;(a!==0||h<_)&&m!==-1;m--,h++)a+=n*f[m]>>>0,f[m]=a%256>>>0,a=a/256>>>0;if(a!==0)throw new Error("Non-zero carry");_=h,s++}let g=c-_;for(;g!==c&&f[g]===0;)g++;let p=new Uint8Array(d+(c-g)),P=d;for(;g!==c;)p[P++]=f[g++];return p}i(I,"decodeUnsafe");function Z(r){let s=I(r);if(s)return s;throw new Error("Non-base"+n+" character")}return i(Z,"decode"),{encode:L,decodeUnsafe:I,decode:Z}}i(F,"base");var y=F;var z="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",N=y(z);var A="2024-03-14",C=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function b(){return new u({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:A,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:C[A]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}i(b,"getMockEnvironment");var u=class e{static{i(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=b()),this.#e}constructor({build:t,runtime:n}){let o;try{if(n.__ZUPLO_CONFIG){let l=atob(n.__ZUPLO_CONFIG);o=JSON.parse(l)}if(n.ZUPLO_SYSTEM_CONFIGURATIONS){let l=new TextDecoder().decode(N.decode(n.ZUPLO_SYSTEM_CONFIGURATIONS)),E=JSON.parse(l);for(let L of Object.keys(E))n[L]=E[L]}}catch(l){console.error("Failed to parse runtime configuration",l)}this.config=o??{},this.build=t,this.runtime=n,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var Y=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function R(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!Y.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}i(R,"isRestrictedEnvVariableName");function T(e){return!!e.startsWith("ZUPLO_")}i(T,"isZuploReadableEnvVariableName");var ae=new Proxy({},{get(e,t){let n=String(t);switch(n){case"ZUPLO_ENVIRONMENT_TYPE":return u.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return u.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return u.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return u.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return u.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return u.instance.build.BUILD_ID}if(!(R(n)&&!T(n)))return u.instance.runtime[n]}});function v(e,t,n){return`_${O(e+"_"+t+"_"+n)}`}i(v,"getRawOperationDataIdentifierName");function D(e,t,n,o){return`_${O(e.toLowerCase())}_`+t.toLowerCase()+"_"+n.toLowerCase()+`_${o.toLowerCase()}`}i(D,"getIdForParameterSchema");function S(e,t,n){return`_${O(e.toLowerCase())}_`+t.toLowerCase()+`_rb_${O(n.toLowerCase())}`}i(S,"getIdForRequestBodySchema");function M(e,t){return`_${O(e)}__${O(t)}`}i(M,"getIdForRefSchema");function O(e){let t=[];for(let n=0;n<e.length;n++){let o=e.charCodeAt(n);o>=48&&o<=57||o>=65&&o<=90||o>=97&&o<=122?t.push(e.charAt(n)):t.push("_")}return t.join("")}i(O,"sanitizedIdentifierName");
|
|
26
26
|
/*! For license information please see index.js.LEGAL.txt */
|
|
@@ -22,15 +22,15 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
"use strict";var
|
|
26
|
-
`).map(
|
|
27
|
-
`)>-1&&(g
|
|
28
|
-
`).map(function(
|
|
29
|
-
`).substr(2):
|
|
30
|
-
`+
|
|
31
|
-
`).map(function(
|
|
32
|
-
`))):
|
|
33
|
-
`)>=0&&u++,
|
|
25
|
+
"use strict";var Ue=Object.create;var P=Object.defineProperty;var Se=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var Pe=Object.getPrototypeOf,Ne=Object.prototype.hasOwnProperty;var n=(e,t)=>P(e,"name",{value:t,configurable:!0});var N=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ie=(e,t)=>{for(var r in t)P(e,r,{get:t[r],enumerable:!0})},X=(e,t,r,u)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Ce(t))!Ne.call(e,s)&&s!==r&&P(e,s,{get:()=>t[s],enumerable:!(u=Se(t,s))||u.enumerable});return e};var ve=(e,t,r)=>(r=e!=null?Ue(Pe(e)):{},X(t||!e||!e.__esModule?P(r,"default",{value:e,enumerable:!0}):r,e)),Me=e=>X(P({},"__esModule",{value:!0}),e);var ue=N(i=>{"use strict";Object.defineProperty(i,"__esModule",{value:!0});i.generateColor=i.colorFunctions=i.stripColor=i.bgRgb24=i.rgb24=i.bgRgb8=i.rgb8=i.bgBrightWhite=i.bgBrightCyan=i.bgBrightMagenta=i.bgBrightBlue=i.bgBrightYellow=i.bgBrightGreen=i.bgBrightRed=i.bgBrightBlack=i.bgWhite=i.bgCyan=i.bgMagenta=i.bgBlue=i.bgYellow=i.bgGreen=i.bgRed=i.bgBlack=i.brightWhite=i.brightCyan=i.brightMagenta=i.brightBlue=i.brightYellow=i.brightGreen=i.brightRed=i.brightBlack=i.gray=i.white=i.cyan=i.magenta=i.blue=i.yellow=i.green=i.red=i.black=i.strikethrough=i.hidden=i.inverse=i.underline=i.italic=i.dim=i.bold=i.reset=i.getColorEnabled=i.setColorEnabled=void 0;var Q=!0,j=!Q;function ze(e){Q||(j=e)}n(ze,"setColorEnabled");i.setColorEnabled=ze;function Be(){return j}n(Be,"getColorEnabled");i.getColorEnabled=Be;function l(e,t){return{open:`\x1B[${e.join(";")}m`,close:`\x1B[${t}m`,regexp:new RegExp(`\\x1b\\[${t}m`,"g")}}n(l,"code");function a(e,t){return j?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}n(a,"run");function xe(e){return a(e,l([0],0))}n(xe,"reset");i.reset=xe;function ke(e){return a(e,l([1],22))}n(ke,"bold");i.bold=ke;function Ze(e){return a(e,l([2],22))}n(Ze,"dim");i.dim=Ze;function De(e){return a(e,l([3],23))}n(De,"italic");i.italic=De;function je(e){return a(e,l([4],24))}n(je,"underline");i.underline=je;function Fe(e){return a(e,l([7],27))}n(Fe,"inverse");i.inverse=Fe;function $e(e){return a(e,l([8],28))}n($e,"hidden");i.hidden=$e;function He(e){return a(e,l([9],29))}n(He,"strikethrough");i.strikethrough=He;function Ge(e){return a(e,l([30],39))}n(Ge,"black");i.black=Ge;function ee(e){return a(e,l([31],39))}n(ee,"red");i.red=ee;function te(e){return a(e,l([32],39))}n(te,"green");i.green=te;function ne(e){return a(e,l([33],39))}n(ne,"yellow");i.yellow=ne;function re(e){return a(e,l([34],39))}n(re,"blue");i.blue=re;function ie(e){return a(e,l([35],39))}n(ie,"magenta");i.magenta=ie;function oe(e){return a(e,l([36],39))}n(oe,"cyan");i.cyan=oe;function Ye(e){return a(e,l([37],39))}n(Ye,"white");i.white=Ye;function Ve(e){return se(e)}n(Ve,"gray");i.gray=Ve;function se(e){return a(e,l([90],39))}n(se,"brightBlack");i.brightBlack=se;function qe(e){return a(e,l([91],39))}n(qe,"brightRed");i.brightRed=qe;function We(e){return a(e,l([92],39))}n(We,"brightGreen");i.brightGreen=We;function Je(e){return a(e,l([93],39))}n(Je,"brightYellow");i.brightYellow=Je;function Ke(e){return a(e,l([94],39))}n(Ke,"brightBlue");i.brightBlue=Ke;function Xe(e){return a(e,l([95],39))}n(Xe,"brightMagenta");i.brightMagenta=Xe;function Qe(e){return a(e,l([96],39))}n(Qe,"brightCyan");i.brightCyan=Qe;function et(e){return a(e,l([97],39))}n(et,"brightWhite");i.brightWhite=et;function tt(e){return a(e,l([40],49))}n(tt,"bgBlack");i.bgBlack=tt;function nt(e){return a(e,l([41],49))}n(nt,"bgRed");i.bgRed=nt;function rt(e){return a(e,l([42],49))}n(rt,"bgGreen");i.bgGreen=rt;function it(e){return a(e,l([43],49))}n(it,"bgYellow");i.bgYellow=it;function ot(e){return a(e,l([44],49))}n(ot,"bgBlue");i.bgBlue=ot;function st(e){return a(e,l([45],49))}n(st,"bgMagenta");i.bgMagenta=st;function ut(e){return a(e,l([46],49))}n(ut,"bgCyan");i.bgCyan=ut;function ct(e){return a(e,l([47],49))}n(ct,"bgWhite");i.bgWhite=ct;function lt(e){return a(e,l([100],49))}n(lt,"bgBrightBlack");i.bgBrightBlack=lt;function at(e){return a(e,l([101],49))}n(at,"bgBrightRed");i.bgBrightRed=at;function gt(e){return a(e,l([102],49))}n(gt,"bgBrightGreen");i.bgBrightGreen=gt;function ft(e){return a(e,l([103],49))}n(ft,"bgBrightYellow");i.bgBrightYellow=ft;function ht(e){return a(e,l([104],49))}n(ht,"bgBrightBlue");i.bgBrightBlue=ht;function dt(e){return a(e,l([105],49))}n(dt,"bgBrightMagenta");i.bgBrightMagenta=dt;function pt(e){return a(e,l([106],49))}n(pt,"bgBrightCyan");i.bgBrightCyan=pt;function mt(e){return a(e,l([107],49))}n(mt,"bgBrightWhite");i.bgBrightWhite=mt;function w(e,t=255,r=0){return Math.trunc(Math.max(Math.min(e,t),r))}n(w,"clampAndTruncate");function bt(e,t){return a(e,l([38,5,w(t)],39))}n(bt,"rgb8");i.rgb8=bt;function _t(e,t){return a(e,l([48,5,w(t)],49))}n(_t,"bgRgb8");i.bgRgb8=_t;function yt(e,t){return typeof t=="number"?a(e,l([38,2,t>>16&255,t>>8&255,t&255],39)):a(e,l([38,2,w(t.r),w(t.g),w(t.b)],39))}n(yt,"rgb24");i.rgb24=yt;function Et(e,t){return typeof t=="number"?a(e,l([48,2,t>>16&255,t>>8&255,t&255],49)):a(e,l([48,2,w(t.r),w(t.g),w(t.b)],49))}n(Et,"bgRgb24");i.bgRgb24=Et;var Ot=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");function Rt(e){return e.replace(Ot,"")}n(Rt,"stripColor");i.stripColor=Rt;i.colorFunctions=[ee,te,ne,re,ie,oe];function wt(e){let t=0,r=e.length,u=0;if(r>0)for(;u<r;)t=(t<<5)-t+e.charCodeAt(u++)|0;return t}n(wt,"hashCode");function Lt(e){let t=Math.abs(wt(e));return i.colorFunctions[t%i.colorFunctions.length]}n(Lt,"generateColor");i.generateColor=Lt});var ce=N(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.format=void 0;function Tt(e,t,...r){let u=0,s=r.length,f=String(t).replace(/%[sdjoO%]/g,o=>{if(o==="%%")return"%";if(u>=s)return o;switch(o){case"%s":return String(r[u++]);case"%d":return Number(r[u++]).toString();case"%o":return e(r[u++]).split(`
|
|
26
|
+
`).map(g=>g.trim()).join(" ");case"%O":return e(r[u++]);case"%j":try{return JSON.stringify(r[u++])}catch{return"[Circular]"}default:return o}});for(let o of r.splice(u))o===null||!(typeof o=="object"&&o!==null)?f+=" "+o:f+=" "+e(o);return f}n(Tt,"format");M.format=Tt});var de=N(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.inspect=void 0;function U(e,t,r,u){let s={seen:[],stylize:At,showHidden:t??!1,depth:r??2,colors:u??!1,customInspect:!0};return s.colors&&(s.stylize=St),z(s,e,s.depth)}n(U,"inspect");B.inspect=U;U.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};U.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function At(e,t){return e}n(At,"stylizeNoColor");function Ut(e){return typeof e=="boolean"}n(Ut,"isBoolean");function ae(e){return e===void 0}n(ae,"isUndefined");function St(e,t){let r=U.styles[t];return r?"\x1B["+U.colors[r][0]+"m"+e+"\x1B["+U.colors[r][1]+"m":e}n(St,"stylizeWithColor");function F(e){return typeof e=="function"}n(F,"isFunction");function ge(e){return typeof e=="string"}n(ge,"isString");function Ct(e){return typeof e=="number"}n(Ct,"isNumber");function fe(e){return e===null}n(fe,"isNull");function he(e,t){return Object.prototype.hasOwnProperty.call(e,t)}n(he,"hasOwn");function $(e){return V(e)&&q(e)==="[object RegExp]"}n($,"isRegExp");function V(e){return typeof e=="object"&&e!==null}n(V,"isObject");function H(e){return V(e)&&(q(e)==="[object Error]"||e instanceof Error)}n(H,"isError");function le(e){return V(e)&&q(e)==="[object Date]"}n(le,"isDate");function q(e){return Object.prototype.toString.call(e)}n(q,"objectToString");function Pt(e){let t={};return e.forEach(function(r,u){t[r]=!0}),t}n(Pt,"arrayToHash");function Nt(e,t,r,u,s){let f=[];for(let o=0,g=t.length;o<g;++o)he(t,String(o))?f.push(Y(e,t,r,u,String(o),!0)):f.push("");return s.forEach(function(o){o.match(/^\d+$/)||f.push(Y(e,t,r,u,o,!0))}),f}n(Nt,"formatArray");function G(e){return"["+Error.prototype.toString.call(e)+"]"}n(G,"formatError");function z(e,t,r){if(e.customInspect&&t&&F(t.inspect)&&t.inspect!==U&&!(t.constructor&&t.constructor.prototype===t)){let h=t.inspect(r,e);return ge(h)||(h=z(e,h,r)),h}let u=It(e,t);if(u)return u;let s=Object.keys(t),f=Pt(s);try{e.showHidden&&Object.getOwnPropertyNames&&(s=Object.getOwnPropertyNames(t))}catch{}if(H(t)&&(s.indexOf("message")>=0||s.indexOf("description")>=0))return G(t);if(s.length===0){if(F(t)){let h=t.name?": "+t.name:"";return e.stylize("[Function"+h+"]","special")}if($(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(le(t))return e.stylize(Date.prototype.toString.call(t),"date");if(H(t))return G(t)}let o="",g=!1,d=["{","}"];if(Array.isArray(t)&&(g=!0,d=["[","]"]),F(t)&&(o=" [Function"+(t.name?": "+t.name:"")+"]"),$(t)&&(o=" "+RegExp.prototype.toString.call(t)),le(t)&&(o=" "+Date.prototype.toUTCString.call(t)),H(t)&&(o=" "+G(t)),s.length===0&&(!g||t.length==0))return d[0]+o+d[1];if(r<0)return $(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);let c;return g?c=Nt(e,t,r,f,s):c=s.map(function(h){return Y(e,t,r,f,h,g)}),e.seen.pop(),vt(c,o,d)}n(z,"formatValue");function Y(e,t,r,u,s,f){let o,g,d;d={value:void 0};try{d.value=t[s]}catch{}try{Object.getOwnPropertyDescriptor&&(d=Object.getOwnPropertyDescriptor(t,s)||d)}catch{}if(d.get?d.set?g=e.stylize("[Getter/Setter]","special"):g=e.stylize("[Getter]","special"):d.set&&(g=e.stylize("[Setter]","special")),he(u,s)||(o="["+s+"]"),g||(e.seen.indexOf(d.value)<0?(fe(r)?g=z(e,d.value,null):g=z(e,d.value,r-1),g.indexOf(`
|
|
27
|
+
`)>-1&&(f?g=g.split(`
|
|
28
|
+
`).map(function(c){return" "+c}).join(`
|
|
29
|
+
`).substr(2):g=`
|
|
30
|
+
`+g.split(`
|
|
31
|
+
`).map(function(c){return" "+c}).join(`
|
|
32
|
+
`))):g=e.stylize("[Circular]","special")),ae(o)){if(f&&s.match(/^\d+$/))return g;o=JSON.stringify(""+s),o.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)?(o=o.substr(1,o.length-2),o=e.stylize(o,"name")):(o=o.replace(/'/g,"\\'").replace(/\\"/g,'"').replace(/(^"|"$)/g,"'"),o=e.stylize(o,"string"))}return o+": "+g}n(Y,"formatProperty");function It(e,t){if(ae(t))return e.stylize("undefined","undefined");if(ge(t)){let r="'"+JSON.stringify(t).replace(/^"|"$/g,"").replace(/'/g,"\\'").replace(/\\"/g,'"')+"'";return e.stylize(r,"string")}if(Ct(t))return e.stylize(""+t,"number");if(Ut(t))return e.stylize(""+t,"boolean");if(fe(t))return e.stylize("null","null")}n(It,"formatPrimitive");function vt(e,t,r){let u=0;return e.reduce(function(f,o){return u++,o.indexOf(`
|
|
33
|
+
`)>=0&&u++,f+o.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?r[0]+(t===""?"":t+`
|
|
34
34
|
`)+" "+e.join(`,
|
|
35
|
-
`)+" "+i[1]:i[0]+t+" "+e.join(", ")+" "+i[1]}n(Ot,"reduceToSingleString")});var oe=R(w=>{"use strict";Object.defineProperty(w,"__esModule",{value:!0});w.format=void 0;var Rt=X(),Lt=ie(),Tt=n((e,...t)=>(0,Rt.format)(Lt.inspect,e,t),"format");w.format=Tt});var ue=R(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.debug=m.withoutEnv=m.Debugger=void 0;var Pt=K(),Ct=oe(),S=class{static{n(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,i){this.manager=t,this.ns=i,this.color=(0,Pt.generateColor)(i),this.last=0,this.enabled=t.enabled.some(u=>u.test(i))}log(...t){if(!this.enabled)return;let i,u=t[0];typeof u=="function"?i=u():i=String(u);let s=Date.now()-(this.last||Date.now());i=(0,Ct.format)(i,...t);let g=`${this.color(this.ns)} ${i} ${this.color(`+${s}ms`)}`;console.log(g),this.last=Date.now()}};m.Debugger=S;var U=class{static{n(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function se(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}n(se,"extract");var L;function wt(e){e||(e=[]),typeof e=="string"&&(e=se(e)),L=new U(e)}n(wt,"withoutEnv");m.withoutEnv=wt;function St(e){let t=globalThis.DEBUG;L||(L=new U(se(t)));let i=new S(L,e);return L.debuggers.set(e,i),Object.assign(i.log.bind(i),{self:i})}n(St,"debug");m.debug=St});var Mt={};ye(Mt,{PdpService:()=>H});module.exports=Re(Mt);var ge=Oe(ue());var E=class extends Error{static{n(this,"RuntimeError")}extensionMembers;constructor(t,i){typeof t=="string"?super(t,i):(super(t.message,i),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}};var Z="2024-03-14",ce=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function le(){return new _({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:Z,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:ce[Z]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}n(le,"getMockEnvironment");var _=class e{static{n(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=le()),this.#e}constructor({build:t,runtime:i}){let u;try{if(i.__ZUPLO_CONFIG){let s=atob(i.__ZUPLO_CONFIG);u=JSON.parse(s)}}catch{console.warn("Failed to parse runtime configuration")}this.config=u??{},this.build=t,this.runtime=i,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var y=(0,ge.debug)("zuplo:runtime:external-service");function Ut(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=_.instance.runtime;if(t&&t!=="undefined")try{let i=atob(t);e=JSON.parse(i)}catch{}return e}n(Ut,"getServiceAuth");async function fe(e,t){let i=Ut();if(i)if(y(`Using external service auth. ClientId: ${i.clientId})`),typeof e=="string"){let u=new URL(e),s=u.hostname,g=t??{},o=new Headers(g.headers||{});o.set("CF-Access-Client-Id",i.clientId),o.set("CF-Access-Client-Secret",i.clientSecret),g.headers=o;let a;if(i.customServiceMapping&&i.customServiceMapping[s])a=`https://${i.customServiceMapping[s]}`;else if(_.instance.useLegacyServiceRouting)a=`https://${s}.zuptunnel.com`;else{y("Using sha256 service routing");let d=_.instance.build;if(d.ACCOUNT_NAME&&d.PROJECT_NAME&&d.ENVIRONMENT_TYPE)a=`https://${await At(s,d.ACCOUNT_NAME,d.PROJECT_NAME,d.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw y("Cannot use sha256 service routing, missing build variables"),new E("Failed to generate fully qualified tunnel url.")}let f=new URL(`${a}${u.pathname}${u.search}`);y(`Calling external service: ${f.toString()}`);let h=await A.fetch(f.toString(),g);if(h.status===403&&h.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:i.clientId,tunnelHost:a}),new E("Could not connect to secure tunnel.");return h}else throw y("Cannot call external service with Request object"),new E("Currently, we only support fetch(<some_string>, ...).");else throw y("There is no external service auth configured for this zup."),new E("There are no external services configured for this zup.")}n(fe,"externalServiceHandler");async function At(e,t,i,u){let s=e.toLowerCase(),g=t.toLowerCase(),o=i.toLowerCase(),a=It(u);y(`Hashing service name: ${g}-${s}.${g}-${o}-${a}`);let f=await ae(`${g}-${s}`),h=await ae(`${g}-${o}-${a}`);return`${f}.${h}`}n(At,"hashServiceName");async function ae(e){let t=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(g=>g.toString(16).padStart(2,"0")).join("").slice(0,-1)}n(ae,"hashSegment");function It(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}n(It,"sanitizeEnvironmentType");var he=new Map;he.set("service:",fe);var de=globalThis.fetch;function D(e,t){let i=Nt(t);if(typeof e=="string"){let u=new URL(e),s=he.get(u.protocol);return s?s(e,i):de(e,i)}else return de(e,i)}n(D,"internalFetch");globalThis.fetch=D;var Nt=n(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let i=e;return i.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var vt={fetch:D},A=vt;var H=class{constructor(t){this.options=t;this.authHeader=`Basic ${btoa(t.pdpUsername+":"+t.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",t.pdpUrl).toString()}static{n(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(t){let i=await A.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!i.ok)throw new Error(`Request to PDP service failed with response status ${i.status}.`);return await i.json()}};
|
|
35
|
+
`)+" "+r[1]:r[0]+t+" "+e.join(", ")+" "+r[1]}n(vt,"reduceToSingleString")});var pe=N(x=>{"use strict";Object.defineProperty(x,"__esModule",{value:!0});x.format=void 0;var Mt=ce(),zt=de(),Bt=n((e,...t)=>(0,Mt.format)(zt.inspect,e,t),"format");x.format=Bt});var be=N(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.debug=L.withoutEnv=L.Debugger=void 0;var xt=ue(),kt=pe(),k=class{static{n(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,r){this.manager=t,this.ns=r,this.color=(0,xt.generateColor)(r),this.last=0,this.enabled=t.enabled.some(u=>u.test(r))}log(...t){if(!this.enabled)return;let r,u=t[0];typeof u=="function"?r=u():r=String(u);let s=Date.now()-(this.last||Date.now());r=(0,kt.format)(r,...t);let f=`${this.color(this.ns)} ${r} ${this.color(`+${s}ms`)}`;console.log(f),this.last=Date.now()}};L.Debugger=k;var Z=class{static{n(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function me(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}n(me,"extract");var I;function Zt(e){e||(e=[]),typeof e=="string"&&(e=me(e)),I=new Z(e)}n(Zt,"withoutEnv");L.withoutEnv=Zt;function Dt(e){let t=globalThis.DEBUG;I||(I=new Z(me(t)));let r=new k(I,e);return I.debuggers.set(e,r),Object.assign(r.log.bind(r),{self:r})}n(Dt,"debug");L.debug=Dt});var qt={};Ie(qt,{PdpService:()=>K});module.exports=Me(qt);var we=ve(be());var S=class extends Error{static{n(this,"RuntimeError")}extensionMembers;constructor(t,r){typeof t=="string"?super(t,r):(super(t.message,r),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}};function jt(e){if(e.length>=255)throw new TypeError("Alphabet too long");let t=new Uint8Array(256);for(let c=0;c<t.length;c++)t[c]=255;for(let c=0;c<e.length;c++){let h=e.charAt(c),m=h.charCodeAt(0);if(t[m]!==255)throw new TypeError(h+" is ambiguous");t[m]=c}let r=e.length,u=e.charAt(0),s=Math.log(r)/Math.log(256),f=Math.log(256)/Math.log(r);function o(c){if(c instanceof Uint8Array||(ArrayBuffer.isView(c)?c=new Uint8Array(c.buffer,c.byteOffset,c.byteLength):Array.isArray(c)&&(c=Uint8Array.from(c))),!(c instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(c.length===0)return"";let h=0,m=0,b=0,y=c.length;for(;b!==y&&c[b]===0;)b++,h++;let E=(y-b)*f+1>>>0,_=new Uint8Array(E);for(;b!==y;){let p=c[b],A=0;for(let R=E-1;(p!==0||A<m)&&R!==-1;R--,A++)p+=256*_[R]>>>0,_[R]=p%r>>>0,p=p/r>>>0;if(p!==0)throw new Error("Non-zero carry");m=A,b++}let O=E-m;for(;O!==E&&_[O]===0;)O++;let v=u.repeat(h);for(;O<E;++O)v+=e.charAt(_[O]);return v}n(o,"encode");function g(c){if(typeof c!="string")throw new TypeError("Expected String");if(c.length===0)return new Uint8Array;let h=0,m=0,b=0;for(;c[h]===u;)m++,h++;let y=(c.length-h)*s+1>>>0,E=new Uint8Array(y);for(;c[h];){let p=t[c.charCodeAt(h)];if(p===255)return;let A=0;for(let R=y-1;(p!==0||A<b)&&R!==-1;R--,A++)p+=r*E[R]>>>0,E[R]=p%256>>>0,p=p/256>>>0;if(p!==0)throw new Error("Non-zero carry");b=A,h++}let _=y-b;for(;_!==y&&E[_]===0;)_++;let O=new Uint8Array(m+(y-_)),v=m;for(;_!==y;)O[v++]=E[_++];return O}n(g,"decodeUnsafe");function d(c){let h=g(c);if(h)return h;throw new Error("Non-base"+r+" character")}return n(d,"decode"),{encode:o,decodeUnsafe:g,decode:d}}n(jt,"base");var _e=jt;var Ft="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ye=_e(Ft);var W="2024-03-14",Ee=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function Oe(){return new T({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:W,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:Ee[W]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}n(Oe,"getMockEnvironment");var T=class e{static{n(this,"Environment")}config;static#e;static#t=!1;static initialize(t){this.#e||(this.#e=new e(t),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=Oe()),this.#e}constructor({build:t,runtime:r}){let u;try{if(r.__ZUPLO_CONFIG){let s=atob(r.__ZUPLO_CONFIG);u=JSON.parse(s)}if(r.ZUPLO_SYSTEM_CONFIGURATIONS){let s=new TextDecoder().decode(ye.decode(r.ZUPLO_SYSTEM_CONFIGURATIONS)),f=JSON.parse(s);for(let o of Object.keys(f))r[o]=f[o]}}catch(s){console.error("Failed to parse runtime configuration",s)}this.config=u??{},this.build=t,this.runtime=r,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};var C=(0,we.debug)("zuplo:runtime:external-service");function $t(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=T.instance.runtime;if(t&&t!=="undefined")try{let r=atob(t);e=JSON.parse(r)}catch{}return e}n($t,"getServiceAuth");async function Le(e,t){let r=$t();if(r)if(C(`Using external service auth. ClientId: ${r.clientId})`),typeof e=="string"){let u=new URL(e),s=u.hostname,f=t??{},o=new Headers(f.headers||{});o.set("CF-Access-Client-Id",r.clientId),o.set("CF-Access-Client-Secret",r.clientSecret),f.headers=o;let g;if(r.customServiceMapping&&r.customServiceMapping[s])g=`https://${r.customServiceMapping[s]}`;else if(T.instance.useLegacyServiceRouting)g=`https://${s}.zuptunnel.com`;else{C("Using sha256 service routing");let h=T.instance.build;if(h.ACCOUNT_NAME&&h.PROJECT_NAME&&h.ENVIRONMENT_TYPE)g=`https://${await Ht(s,h.ACCOUNT_NAME,h.PROJECT_NAME,h.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw C("Cannot use sha256 service routing, missing build variables"),new S("Failed to generate fully qualified tunnel url.")}let d=new URL(`${g}${u.pathname}${u.search}`);C(`Calling external service: ${d.toString()}`);let c=await D.fetch(d.toString(),f);if(c.status===403&&c.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:r.clientId,tunnelHost:g}),new S("Could not connect to secure tunnel.");return c}else throw C("Cannot call external service with Request object"),new S("Currently, we only support fetch(<some_string>, ...).");else throw C("There is no external service auth configured for this zup."),new S("There are no external services configured for this zup.")}n(Le,"externalServiceHandler");async function Ht(e,t,r,u){let s=e.toLowerCase(),f=t.toLowerCase(),o=r.toLowerCase(),g=Gt(u);C(`Hashing service name: ${f}-${s}.${f}-${o}-${g}`);let d=await Re(`${f}-${s}`),c=await Re(`${f}-${o}-${g}`);return`${d}.${c}`}n(Ht,"hashServiceName");async function Re(e){let t=new TextEncoder().encode(e),r=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(r)).map(f=>f.toString(16).padStart(2,"0")).join("").slice(0,-1)}n(Re,"hashSegment");function Gt(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}n(Gt,"sanitizeEnvironmentType");var Ae=new Map;Ae.set("service:",Le);var Te=globalThis.fetch;function J(e,t){let r=Yt(t);if(typeof e=="string"){let u=new URL(e),s=Ae.get(u.protocol);return s?s(e,r):Te(e,r)}else return Te(e,r)}n(J,"internalFetch");globalThis.fetch=J;var Yt=n(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 Vt={fetch:J},D=Vt;var K=class{constructor(t){this.options=t;this.authHeader=`Basic ${btoa(t.pdpUsername+":"+t.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",t.pdpUrl).toString()}static{n(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(t){let r=await D.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!r.ok)throw new Error(`Request to PDP service failed with response status ${r.status}.`);return await r.json()}};
|
|
36
36
|
/*! For license information please see exports.js.LEGAL.txt */
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a as E}from"./chunk-
|
|
25
|
+
import{a as E}from"./chunk-HAXIE4MQ.js";import{a as r,b as R,c as he}from"./chunk-PPV7V43C.js";var V=R(n=>{"use strict";Object.defineProperty(n,"__esModule",{value:!0});n.generateColor=n.colorFunctions=n.stripColor=n.bgRgb24=n.rgb24=n.bgRgb8=n.rgb8=n.bgBrightWhite=n.bgBrightCyan=n.bgBrightMagenta=n.bgBrightBlue=n.bgBrightYellow=n.bgBrightGreen=n.bgBrightRed=n.bgBrightBlack=n.bgWhite=n.bgCyan=n.bgMagenta=n.bgBlue=n.bgYellow=n.bgGreen=n.bgRed=n.bgBlack=n.brightWhite=n.brightCyan=n.brightMagenta=n.brightBlue=n.brightYellow=n.brightGreen=n.brightRed=n.brightBlack=n.gray=n.white=n.cyan=n.magenta=n.blue=n.yellow=n.green=n.red=n.black=n.strikethrough=n.hidden=n.inverse=n.underline=n.italic=n.dim=n.bold=n.reset=n.getColorEnabled=n.setColorEnabled=void 0;var F=!0,$=!F;function pe(e){F||($=e)}r(pe,"setColorEnabled");n.setColorEnabled=pe;function de(){return $}r(de,"getColorEnabled");n.getColorEnabled=de;function s(e,t){return{open:`\x1B[${e.join(";")}m`,close:`\x1B[${t}m`,regexp:new RegExp(`\\x1b\\[${t}m`,"g")}}r(s,"code");function c(e,t){return $?`${t.open}${e.replace(t.regexp,t.open)}${t.close}`:e}r(c,"run");function be(e){return c(e,s([0],0))}r(be,"reset");n.reset=be;function me(e){return c(e,s([1],22))}r(me,"bold");n.bold=me;function ye(e){return c(e,s([2],22))}r(ye,"dim");n.dim=ye;function we(e){return c(e,s([3],23))}r(we,"italic");n.italic=we;function Re(e){return c(e,s([4],24))}r(Re,"underline");n.underline=Re;function Ce(e){return c(e,s([7],27))}r(Ce,"inverse");n.inverse=Ce;function Ee(e){return c(e,s([8],28))}r(Ee,"hidden");n.hidden=Ee;function Se(e){return c(e,s([9],29))}r(Se,"strikethrough");n.strikethrough=Se;function Oe(e){return c(e,s([30],39))}r(Oe,"black");n.black=Oe;function L(e){return c(e,s([31],39))}r(L,"red");n.red=L;function Y(e){return c(e,s([32],39))}r(Y,"green");n.green=Y;function D(e){return c(e,s([33],39))}r(D,"yellow");n.yellow=D;function G(e){return c(e,s([34],39))}r(G,"blue");n.blue=G;function J(e){return c(e,s([35],39))}r(J,"magenta");n.magenta=J;function W(e){return c(e,s([36],39))}r(W,"cyan");n.cyan=W;function Be(e){return c(e,s([37],39))}r(Be,"white");n.white=Be;function ze(e){return Z(e)}r(ze,"gray");n.gray=ze;function Z(e){return c(e,s([90],39))}r(Z,"brightBlack");n.brightBlack=Z;function Ae(e){return c(e,s([91],39))}r(Ae,"brightRed");n.brightRed=Ae;function Ne(e){return c(e,s([92],39))}r(Ne,"brightGreen");n.brightGreen=Ne;function Me(e){return c(e,s([93],39))}r(Me,"brightYellow");n.brightYellow=Me;function $e(e){return c(e,s([94],39))}r($e,"brightBlue");n.brightBlue=$e;function ve(e){return c(e,s([95],39))}r(ve,"brightMagenta");n.brightMagenta=ve;function xe(e){return c(e,s([96],39))}r(xe,"brightCyan");n.brightCyan=xe;function Te(e){return c(e,s([97],39))}r(Te,"brightWhite");n.brightWhite=Te;function _e(e){return c(e,s([40],49))}r(_e,"bgBlack");n.bgBlack=_e;function je(e){return c(e,s([41],49))}r(je,"bgRed");n.bgRed=je;function Ie(e){return c(e,s([42],49))}r(Ie,"bgGreen");n.bgGreen=Ie;function Pe(e){return c(e,s([43],49))}r(Pe,"bgYellow");n.bgYellow=Pe;function Ue(e){return c(e,s([44],49))}r(Ue,"bgBlue");n.bgBlue=Ue;function He(e){return c(e,s([45],49))}r(He,"bgMagenta");n.bgMagenta=He;function qe(e){return c(e,s([46],49))}r(qe,"bgCyan");n.bgCyan=qe;function ke(e){return c(e,s([47],49))}r(ke,"bgWhite");n.bgWhite=ke;function Fe(e){return c(e,s([100],49))}r(Fe,"bgBrightBlack");n.bgBrightBlack=Fe;function Le(e){return c(e,s([101],49))}r(Le,"bgBrightRed");n.bgBrightRed=Le;function Ye(e){return c(e,s([102],49))}r(Ye,"bgBrightGreen");n.bgBrightGreen=Ye;function De(e){return c(e,s([103],49))}r(De,"bgBrightYellow");n.bgBrightYellow=De;function Ge(e){return c(e,s([104],49))}r(Ge,"bgBrightBlue");n.bgBrightBlue=Ge;function Je(e){return c(e,s([105],49))}r(Je,"bgBrightMagenta");n.bgBrightMagenta=Je;function We(e){return c(e,s([106],49))}r(We,"bgBrightCyan");n.bgBrightCyan=We;function Ze(e){return c(e,s([107],49))}r(Ze,"bgBrightWhite");n.bgBrightWhite=Ze;function b(e,t=255,i=0){return Math.trunc(Math.max(Math.min(e,t),i))}r(b,"clampAndTruncate");function Ve(e,t){return c(e,s([38,5,b(t)],39))}r(Ve,"rgb8");n.rgb8=Ve;function Xe(e,t){return c(e,s([48,5,b(t)],49))}r(Xe,"bgRgb8");n.bgRgb8=Xe;function Ke(e,t){return typeof t=="number"?c(e,s([38,2,t>>16&255,t>>8&255,t&255],39)):c(e,s([38,2,b(t.r),b(t.g),b(t.b)],39))}r(Ke,"rgb24");n.rgb24=Ke;function Qe(e,t){return typeof t=="number"?c(e,s([48,2,t>>16&255,t>>8&255,t&255],49)):c(e,s([48,2,b(t.r),b(t.g),b(t.b)],49))}r(Qe,"bgRgb24");n.bgRgb24=Qe;var et=new RegExp(["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))"].join("|"),"g");function tt(e){return e.replace(et,"")}r(tt,"stripColor");n.stripColor=tt;n.colorFunctions=[L,Y,D,G,J,W];function nt(e){let t=0,i=e.length,u=0;if(i>0)for(;u<i;)t=(t<<5)-t+e.charCodeAt(u++)|0;return t}r(nt,"hashCode");function rt(e){let t=Math.abs(nt(e));return n.colorFunctions[t%n.colorFunctions.length]}r(rt,"generateColor");n.generateColor=rt});var X=R(S=>{"use strict";Object.defineProperty(S,"__esModule",{value:!0});S.format=void 0;function it(e,t,...i){let u=0,a=i.length,g=String(t).replace(/%[sdjoO%]/g,o=>{if(o==="%%")return"%";if(u>=a)return o;switch(o){case"%s":return String(i[u++]);case"%d":return Number(i[u++]).toString();case"%o":return e(i[u++]).split(`
|
|
26
26
|
`).map(l=>l.trim()).join(" ");case"%O":return e(i[u++]);case"%j":try{return JSON.stringify(i[u++])}catch{return"[Circular]"}default:return o}});for(let o of i.splice(u))o===null||!(typeof o=="object"&&o!==null)?g+=" "+o:g+=" "+e(o);return g}r(it,"format");S.format=it});var re=R(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.inspect=void 0;function y(e,t,i,u){let a={seen:[],stylize:ot,showHidden:t??!1,depth:i??2,colors:u??!1,customInspect:!0};return a.colors&&(a.stylize=ct),O(a,e,a.depth)}r(y,"inspect");B.inspect=y;y.colors={bold:[1,22],italic:[3,23],underline:[4,24],inverse:[7,27],white:[37,39],grey:[90,39],black:[30,39],blue:[34,39],cyan:[36,39],green:[32,39],magenta:[35,39],red:[31,39],yellow:[33,39]};y.styles={special:"cyan",number:"yellow",boolean:"yellow",undefined:"grey",null:"bold",string:"green",date:"magenta",regexp:"red"};function ot(e,t){return e}r(ot,"stylizeNoColor");function st(e){return typeof e=="boolean"}r(st,"isBoolean");function Q(e){return e===void 0}r(Q,"isUndefined");function ct(e,t){let i=y.styles[t];return i?"\x1B["+y.colors[i][0]+"m"+e+"\x1B["+y.colors[i][1]+"m":e}r(ct,"stylizeWithColor");function v(e){return typeof e=="function"}r(v,"isFunction");function ee(e){return typeof e=="string"}r(ee,"isString");function ut(e){return typeof e=="number"}r(ut,"isNumber");function te(e){return e===null}r(te,"isNull");function ne(e,t){return Object.prototype.hasOwnProperty.call(e,t)}r(ne,"hasOwn");function x(e){return I(e)&&P(e)==="[object RegExp]"}r(x,"isRegExp");function I(e){return typeof e=="object"&&e!==null}r(I,"isObject");function T(e){return I(e)&&(P(e)==="[object Error]"||e instanceof Error)}r(T,"isError");function K(e){return I(e)&&P(e)==="[object Date]"}r(K,"isDate");function P(e){return Object.prototype.toString.call(e)}r(P,"objectToString");function at(e){let t={};return e.forEach(function(i,u){t[i]=!0}),t}r(at,"arrayToHash");function lt(e,t,i,u,a){let g=[];for(let o=0,l=t.length;o<l;++o)ne(t,String(o))?g.push(j(e,t,i,u,String(o),!0)):g.push("");return a.forEach(function(o){o.match(/^\d+$/)||g.push(j(e,t,i,u,o,!0))}),g}r(lt,"formatArray");function _(e){return"["+Error.prototype.toString.call(e)+"]"}r(_,"formatError");function O(e,t,i){if(e.customInspect&&t&&v(t.inspect)&&t.inspect!==y&&!(t.constructor&&t.constructor.prototype===t)){let h=t.inspect(i,e);return ee(h)||(h=O(e,h,i)),h}let u=gt(e,t);if(u)return u;let a=Object.keys(t),g=at(a);try{e.showHidden&&Object.getOwnPropertyNames&&(a=Object.getOwnPropertyNames(t))}catch{}if(T(t)&&(a.indexOf("message")>=0||a.indexOf("description")>=0))return _(t);if(a.length===0){if(v(t)){let h=t.name?": "+t.name:"";return e.stylize("[Function"+h+"]","special")}if(x(t))return e.stylize(RegExp.prototype.toString.call(t),"regexp");if(K(t))return e.stylize(Date.prototype.toString.call(t),"date");if(T(t))return _(t)}let o="",l=!1,f=["{","}"];if(Array.isArray(t)&&(l=!0,f=["[","]"]),v(t)&&(o=" [Function"+(t.name?": "+t.name:"")+"]"),x(t)&&(o=" "+RegExp.prototype.toString.call(t)),K(t)&&(o=" "+Date.prototype.toUTCString.call(t)),T(t)&&(o=" "+_(t)),a.length===0&&(!l||t.length==0))return f[0]+o+f[1];if(i<0)return x(t)?e.stylize(RegExp.prototype.toString.call(t),"regexp"):e.stylize("[Object]","special");e.seen.push(t);let p;return l?p=lt(e,t,i,g,a):p=a.map(function(h){return j(e,t,i,g,h,l)}),e.seen.pop(),ft(p,o,f)}r(O,"formatValue");function j(e,t,i,u,a,g){let o,l,f;f={value:void 0};try{f.value=t[a]}catch{}try{Object.getOwnPropertyDescriptor&&(f=Object.getOwnPropertyDescriptor(t,a)||f)}catch{}if(f.get?f.set?l=e.stylize("[Getter/Setter]","special"):l=e.stylize("[Getter]","special"):f.set&&(l=e.stylize("[Setter]","special")),ne(u,a)||(o="["+a+"]"),l||(e.seen.indexOf(f.value)<0?(te(i)?l=O(e,f.value,null):l=O(e,f.value,i-1),l.indexOf(`
|
|
27
27
|
`)>-1&&(g?l=l.split(`
|
|
28
28
|
`).map(function(p){return" "+p}).join(`
|
|
@@ -33,4 +33,4 @@ import{a as E}from"./chunk-7HJ5MMZB.js";import{a as r,b as R,c as he}from"./chun
|
|
|
33
33
|
`)>=0&&u++,g+o.replace(/\u001b\[\d\d?m/g,"").length+1},0)>60?i[0]+(t===""?"":t+`
|
|
34
34
|
`)+" "+e.join(`,
|
|
35
35
|
`)+" "+i[1]:i[0]+t+" "+e.join(", ")+" "+i[1]}r(ft,"reduceToSingleString")});var ie=R(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.format=void 0;var ht=X(),pt=re(),dt=r((e,...t)=>(0,ht.format)(pt.inspect,e,t),"format");z.format=dt});var se=R(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.debug=m.withoutEnv=m.Debugger=void 0;var bt=V(),mt=ie(),A=class{static{r(this,"Debugger")}manager;ns;color;last;enabled;constructor(t,i){this.manager=t,this.ns=i,this.color=(0,bt.generateColor)(i),this.last=0,this.enabled=t.enabled.some(u=>u.test(i))}log(...t){if(!this.enabled)return;let i,u=t[0];typeof u=="function"?i=u():i=String(u);let a=Date.now()-(this.last||Date.now());i=(0,mt.format)(i,...t);let g=`${this.color(this.ns)} ${i} ${this.color(`+${a}ms`)}`;console.log(g),this.last=Date.now()}};m.Debugger=A;var N=class{static{r(this,"DebugManager")}debuggers;enabled;constructor(t){this.debuggers=new Map,this.enabled=t??[]}};function oe(e){return!e||e.length===0?[]:(e=e.replace(/\s/g,"").replace(/\*/g,".+"),e.split(",").map(t=>new RegExp(`^${t}$`)))}r(oe,"extract");var C;function yt(e){e||(e=[]),typeof e=="string"&&(e=oe(e)),C=new N(e)}r(yt,"withoutEnv");m.withoutEnv=yt;function wt(e){let t=globalThis.DEBUG;C||(C=new N(oe(t)));let i=new A(C,e);return C.debuggers.set(e,i),Object.assign(i.log.bind(i),{self:i})}r(wt,"debug");m.debug=wt});var H=class extends Error{static{r(this,"SystemError")}constructor(t,i){super(t,i),this.name="InternalError"}},d=class extends Error{static{r(this,"RuntimeError")}extensionMembers;constructor(t,i){typeof t=="string"?super(t,i):(super(t.message,i),this.extensionMembers=t.extensionMembers),this.name="RuntimeError"}},q=class extends d{static{r(this,"ConfigurationError")}constructor(t,i){super(t,i),this.name="ConfigurationError"}},k=class extends d{static{r(this,"FeatureNotEnabledError")}constructor(t,i){super(t,i),this.name="FeatureNotEnabledError"}};var ue=he(se());var w=(0,ue.debug)("zuplo:runtime:external-service");function Rt(){let e,{__ZUPLO_EXTERNAL_SERVICE_TOKEN:t}=E.instance.runtime;if(t&&t!=="undefined")try{let i=atob(t);e=JSON.parse(i)}catch{}return e}r(Rt,"getServiceAuth");async function ae(e,t){let i=Rt();if(i)if(w(`Using external service auth. ClientId: ${i.clientId})`),typeof e=="string"){let u=new URL(e),a=u.hostname,g=t??{},o=new Headers(g.headers||{});o.set("CF-Access-Client-Id",i.clientId),o.set("CF-Access-Client-Secret",i.clientSecret),g.headers=o;let l;if(i.customServiceMapping&&i.customServiceMapping[a])l=`https://${i.customServiceMapping[a]}`;else if(E.instance.useLegacyServiceRouting)l=`https://${a}.zuptunnel.com`;else{w("Using sha256 service routing");let h=E.instance.build;if(h.ACCOUNT_NAME&&h.PROJECT_NAME&&h.ENVIRONMENT_TYPE)l=`https://${await Ct(a,h.ACCOUNT_NAME,h.PROJECT_NAME,h.ENVIRONMENT_TYPE)}.zuptunnel.com`;else throw w("Cannot use sha256 service routing, missing build variables"),new d("Failed to generate fully qualified tunnel url.")}let f=new URL(`${l}${u.pathname}${u.search}`);w(`Calling external service: ${f.toString()}`);let p=await M.fetch(f.toString(),g);if(p.status===403&&p.headers.get("cf-access-domain")!==null)throw console.error("403 Forbidden when calling external service.",{clientId:i.clientId,tunnelHost:l}),new d("Could not connect to secure tunnel.");return p}else throw w("Cannot call external service with Request object"),new d("Currently, we only support fetch(<some_string>, ...).");else throw w("There is no external service auth configured for this zup."),new d("There are no external services configured for this zup.")}r(ae,"externalServiceHandler");async function Ct(e,t,i,u){let a=e.toLowerCase(),g=t.toLowerCase(),o=i.toLowerCase(),l=Et(u);w(`Hashing service name: ${g}-${a}.${g}-${o}-${l}`);let f=await ce(`${g}-${a}`),p=await ce(`${g}-${o}-${l}`);return`${f}.${p}`}r(Ct,"hashServiceName");async function ce(e){let t=new TextEncoder().encode(e),i=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(i)).map(g=>g.toString(16).padStart(2,"0")).join("").slice(0,-1)}r(ce,"hashSegment");function Et(e){let t=e.toLowerCase();switch(t){case"production":case"preview":return t;default:return"working-copy"}}r(Et,"sanitizeEnvironmentType");var ge=new Map;ge.set("service:",ae);var le=globalThis.fetch;function U(e,t){let i=St(t);if(typeof e=="string"){let u=new URL(e),a=ge.get(u.protocol);return a?a(e,i):le(e,i)}else return le(e,i)}r(U,"internalFetch");globalThis.fetch=U;var St=r(e=>{if(!e||e instanceof Request)return e;let t=e;if(!t.zuplo)return e;let i=e;return i.cf={cacheEverything:t.zuplo?.cacheEverything,cacheTtl:t.zuplo?.cacheTtlSeconds},delete e.zuplo,e},"transformInit");var Ot={fetch:U},M=Ot;var fe=class{constructor(t){this.options=t;this.authHeader=`Basic ${btoa(t.pdpUsername+":"+t.pdpPassword)}`,this.authorizationUrl=new URL("/authorize",t.pdpUrl).toString()}static{r(this,"PdpService")}authHeader;authorizationUrl;async makePdpRequest(t){let i=await M.fetch(this.authorizationUrl,{method:"POST",body:JSON.stringify(t),headers:{"Content-Type":"application/xacml+json; charset=UTF-8",[this.options.tokenHeaderName??"Authorization"]:this.authHeader}});if(!i.ok)throw new Error(`Request to PDP service failed with response status ${i.status}.`);return await i.json()}};export{se as a,H as b,d as c,q as d,k as e,M as f,fe as g};
|
|
36
|
-
/*! For license information please see chunk-
|
|
36
|
+
/*! For license information please see chunk-BUNYKRVW.js.LEGAL.txt */
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
|
|
2
|
+
/*---------------------------------------------------------------------------------------------
|
|
3
|
+
* Copyright (c) Zuplo, Inc. All rights reserved.
|
|
4
|
+
*
|
|
5
|
+
* This software and associated documentation files (the "Software") is intended to be used
|
|
6
|
+
* only by Zuplo customers solely to develop and test applications that will be deployed
|
|
7
|
+
* to Zuplo hosted services. You and others in your organization may use these files on your
|
|
8
|
+
* Development Devices solely for the above stated purpose.
|
|
9
|
+
*
|
|
10
|
+
* Outside of uses stated above, no license is granted for any other purpose including
|
|
11
|
+
* without limitation the rights to use, copy, modify, merge, publish, distribute,
|
|
12
|
+
* sublicense, host, and/or sell copies of the Software.
|
|
13
|
+
*
|
|
14
|
+
* The software may include third party components with separate legal notices or governed by
|
|
15
|
+
* other agreements, as described in licenses either embedded in or accompanying the Software.
|
|
16
|
+
*
|
|
17
|
+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
|
18
|
+
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
|
|
19
|
+
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
|
|
20
|
+
* FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
|
|
21
|
+
* OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
|
22
|
+
* DEALINGS IN THE SOFTWARE.
|
|
23
|
+
*--------------------------------------------------------------------------------------------*/
|
|
24
|
+
|
|
25
|
+
import{a as d}from"./chunk-PPV7V43C.js";function N(c){if(c.length>=255)throw new TypeError("Alphabet too long");let _=new Uint8Array(256);for(let e=0;e<_.length;e++)_[e]=255;for(let e=0;e<c.length;e++){let t=c.charAt(e),s=t.charCodeAt(0);if(_[s]!==255)throw new TypeError(t+" is ambiguous");_[s]=e}let i=c.length,h=c.charAt(0),f=Math.log(i)/Math.log(256),E=Math.log(256)/Math.log(i);function p(e){if(e instanceof Uint8Array||(ArrayBuffer.isView(e)?e=new Uint8Array(e.buffer,e.byteOffset,e.byteLength):Array.isArray(e)&&(e=Uint8Array.from(e))),!(e instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(e.length===0)return"";let t=0,s=0,r=0,l=e.length;for(;r!==l&&e[r]===0;)r++,t++;let u=(l-r)*E+1>>>0,o=new Uint8Array(u);for(;r!==l;){let n=e[r],m=0;for(let g=u-1;(n!==0||m<s)&&g!==-1;g--,m++)n+=256*o[g]>>>0,o[g]=n%i>>>0,n=n/i>>>0;if(n!==0)throw new Error("Non-zero carry");s=m,r++}let a=u-s;for(;a!==u&&o[a]===0;)a++;let L=h.repeat(t);for(;a<u;++a)L+=c.charAt(o[a]);return L}d(p,"encode");function T(e){if(typeof e!="string")throw new TypeError("Expected String");if(e.length===0)return new Uint8Array;let t=0,s=0,r=0;for(;e[t]===h;)s++,t++;let l=(e.length-t)*f+1>>>0,u=new Uint8Array(l);for(;e[t];){let n=_[e.charCodeAt(t)];if(n===255)return;let m=0;for(let g=l-1;(n!==0||m<r)&&g!==-1;g--,m++)n+=i*u[g]>>>0,u[g]=n%256>>>0,n=n/256>>>0;if(n!==0)throw new Error("Non-zero carry");r=m,t++}let o=l-r;for(;o!==l&&u[o]===0;)o++;let a=new Uint8Array(s+(l-o)),L=s;for(;o!==l;)a[L++]=u[o++];return a}d(T,"decodeUnsafe");function R(e){let t=T(e);if(t)return t;throw new Error("Non-base"+i+" character")}return d(R,"decode"),{encode:p,decodeUnsafe:T,decode:R}}d(N,"base");var A=N;var b="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",P=A(b);var U="2024-03-14",y=Object.freeze({none:{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2023-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!1,doNotRunHooksOnSystemRoutes:!1,removeAllVendorHeadersExceptListed:!1},"2024-01-15":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0},"2024-03-14":{runOutboundPoliciesOnHandlerOnAllStatuses:!0,doNotRunHooksOnSystemRoutes:!0,removeAllVendorHeadersExceptListed:!0}});function I(){return new O({build:{ACCOUNT_NAME:"mock-account-name",PROJECT_NAME:"mock-project-name",API_VERSION:"0.0.0",BUILD_ID:crypto.randomUUID(),TIMESTAMP:new Date().toISOString(),IS_PRODUCTION:!1,BUILD_ENV:"test",ZUPLO_VERSION:"0.0.0",COMPATIBILITY_DATE:U,ENVIRONMENT_TYPE:"mock-environment-type",GIT_SHA:void 0,IS_LOCAL_DEVELOPMENT:!1,COMPATIBILITY_FLAGS:y[U]},runtime:{RUNTIME_ENV:"test",RUNTIME_STAGE:"test",__ZUPLO_DEPLOYMENT_NAME:"mock-deployment-name",__ZUPLO_LOG_LEVEL:"debug",__ZUPLO_LOG_FORMAT:"pretty",__ZUPLO_MANAGEMENT_API_URL:"",__ZUPLO_RUNTIME_TYPE:"cloudflare",__ZUPLO_AUTH_API_JWT:""}})}d(I,"getMockEnvironment");var O=class c{static{d(this,"Environment")}config;static#e;static#t=!1;static initialize(_){this.#e||(this.#e=new c(_),this.#t=!0)}static get instance(){return this.#t||(console.debug("Environment has not been initialized. This is okay when running tests, a mock environment will be used."),this.#e=I()),this.#e}constructor({build:_,runtime:i}){let h;try{if(i.__ZUPLO_CONFIG){let f=atob(i.__ZUPLO_CONFIG);h=JSON.parse(f)}if(i.ZUPLO_SYSTEM_CONFIGURATIONS){let f=new TextDecoder().decode(P.decode(i.ZUPLO_SYSTEM_CONFIGURATIONS)),E=JSON.parse(f);for(let p of Object.keys(E))i[p]=E[p]}}catch(f){console.error("Failed to parse runtime configuration",f)}this.config=h??{},this.build=_,this.runtime=i,this.instanceId=crypto.randomUUID()}build;runtime;instanceId;get deploymentName(){return this.runtime.__ZUPLO_DEPLOYMENT_NAME??this.config.deployment_name??void 0}get useLegacyServiceRouting(){return this.config.use_legacy_service_routing??void 0}get useProxyForFetchFromZups(){return this.config.use_proxy_for_fetch_from_zups??void 0}get devPortalBaseUrl(){return this.runtime.__ZUPLO_DEV_PORTAL_URL??this.config.dev_portal_url??"https://dev-portal-v4-1.zuplo.com"}get buildAssetsUrl(){return this.runtime.__ZUPLO_BUILD_ASSETS_URL??this.config.build_assets_url??"https://build-assets.zuplo.com"}get remoteLogToken(){return this.runtime.__ZUPLO_REMOTE_LOG_TOKEN??this.config.remote_log_token??void 0}get zuploClientAuthBucketId(){return this.config.zuplo_auth_client_bucket_id??"auth_o8PUdhKxSTOiB794GWPwLQCD"}get managementApiURL(){return this.runtime.__ZUPLO_MANAGEMENT_API_URL??this.config.management_api_url??"https://api.zuplo.com"}get developerApiUrl(){return this.config.developer_api_url??"https://dev.zuplo.com"}get cdnURL(){return this.runtime.__ZUPLO_CDN_URL??this.config.cdn_url??"https://cdn.zuplo.com"}get remoteLogURL(){return this.runtime.__ZUPLO_REMOTE_LOG_URL??this.config.log_event_api??"https://ellie.zuplo.com"}get loggingId(){return this.runtime.__ZUPLO_LOGGING_ID??this.config.logging_id??void 0}get redisURL(){return this.runtime.__ZUPLO_REDIS_URL??this.config.redis_proxy_url??"https://redis-proxy.zuplo.com"}get apiKeyServiceUrl(){return this.runtime.__ZUPLO_API_KEY_SERVICE_URL??this.config.api_key_service_url??"https://apikey.zuplo.com"}get meteringServiceUrl(){return this.config.metering_service_url??"https://meters.zuplo.com"}get authApiJWT(){return this.runtime.__ZUPLO_AUTH_API_JWT??void 0}get authClientId(){return this.runtime.__ZUPLO_AUTH_CLIENT_ID}get authClientSecret(){return this.runtime.__ZUPLO_AUTH_CLIENT_SECRET}get userLogLevel(){return this.runtime.ZUPLO_LOG_LEVEL??this.runtime.__ZUPLO_LOG_LEVEL??this.config.user_log_level??"debug"}get systemLogLevel(){return this.runtime.__ZUPLO_LOG_LEVEL??this.config.system_log_level??"debug"}get logFormat(){return this.runtime.__ZUPLO_LOG_FORMAT??this.config.log_format??"cloudflare"}get isCloudflare(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="cloudflare":this.config.runtime_type?this.config.runtime_type==="cloudflare":typeof WebSocketPair=="function"}get isDeno(){return this.runtime.__ZUPLO_RUNTIME_TYPE?this.runtime.__ZUPLO_RUNTIME_TYPE==="deno":this.config.runtime_type?this.config.runtime_type==="deno":typeof WebSocketPair!="function"}get isLocalDevelopment(){return this.build.IS_LOCAL_DEVELOPMENT}get isTestMode(){return!!this.runtime.__ZUPLO_TEST_MODE}get systemUserAgent(){return`Zuplo/${this.build.ZUPLO_VERSION}`}get loggingEnvironmentType(){return this.isCloudflare?"edge":this.isLocalDevelopment?"local":this.isDeno?"working-copy":"unknown"}get loggingEnvironmentStage(){return this.build.ENVIRONMENT_TYPE==="PRODUCTION"?"production":this.build.ENVIRONMENT_TYPE==="PREVIEW"?"preview":this.isLocalDevelopment?"local":this.isWorkingCopy?"working-copy":"unknown"}get isWorkingCopy(){return this.build.ENVIRONMENT_TYPE==="WORKING_COPY"}};export{O as a};
|
|
26
|
+
/*! For license information please see chunk-HAXIE4MQ.js.LEGAL.txt */
|
|
@@ -22,5 +22,5 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a}from"./chunk-
|
|
26
|
-
/*! For license information please see chunk-
|
|
25
|
+
import{a}from"./chunk-HAXIE4MQ.js";import{a as n}from"./chunk-PPV7V43C.js";var c=(o=>(o.Build="build-data",o.CorsPreflight="cors-preflight",o.DeveloperPortal="developer-portal",o.DeveloperPortalLegacy="developer-portal-legacy",o.StripePlugin="stripe-plugin",o.EmptyGatewayCatchall="empty-gateway-catchall",o.Ping="ping",o.UnmatchedPath="unmatched-path",o))(c||{});var p=["ZUPLO_USER_LOGGER_DATA_DOG_API_KEY","ZUPLO_USER_LOGGER_DATA_DOG_URL","ZUPLO_LOG_LEVEL","ZUPLO_HANDLER_WRITE_LOG_LEVEL"];function _(e){return e.startsWith("__ZUPLO")||e.startsWith("ZUPLO_")?!p.includes(e)&&!e.startsWith("ZUPLO_PUBLIC_"):!1}n(_,"isRestrictedEnvVariableName");function g(e){return!!e.startsWith("ZUPLO_")}n(g,"isZuploReadableEnvVariableName");var f=new Proxy({},{get(e,r){let t=String(r);switch(t){case"ZUPLO_ENVIRONMENT_TYPE":return a.instance.loggingEnvironmentType;case"ZUPLO_ENVIRONMENT_STAGE":return a.instance.loggingEnvironmentStage;case"ZUPLO_ENVIRONMENT_NAME":return a.instance.runtime.__ZUPLO_DEPLOYMENT_NAME;case"ZUPLO_ACCOUNT_NAME":return a.instance.build.ACCOUNT_NAME;case"ZUPLO_PROJECT_NAME":return a.instance.build.PROJECT_NAME;case"ZUPLO_BUILD_ID":return a.instance.build.BUILD_ID}if(!(_(t)&&!g(t)))return a.instance.runtime[t]}});function C(e,r,t){return`_${s(e+"_"+r+"_"+t)}`}n(C,"getRawOperationDataIdentifierName");function h(e,r,t,i){return`_${s(e.toLowerCase())}_`+r.toLowerCase()+"_"+t.toLowerCase()+`_${i.toLowerCase()}`}n(h,"getIdForParameterSchema");function A(e,r,t){return`_${s(e.toLowerCase())}_`+r.toLowerCase()+`_rb_${s(t.toLowerCase())}`}n(A,"getIdForRequestBodySchema");function m(e,r){return`_${s(e)}__${s(r)}`}n(m,"getIdForRefSchema");function s(e){let r=[];for(let t=0;t<e.length;t++){let i=e.charCodeAt(t);i>=48&&i<=57||i>=65&&i<=90||i>=97&&i<=122?r.push(e.charAt(t)):r.push("_")}return r.join("")}n(s,"sanitizedIdentifierName");export{c as a,_ as b,g as c,f as d,C as e,h as f,A as g,m as h,s as i};
|
|
26
|
+
/*! For license information please see chunk-W2THI7KO.js.LEGAL.txt */
|
package/out/esm/index.js
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* DEALINGS IN THE SOFTWARE.
|
|
23
23
|
*--------------------------------------------------------------------------------------------*/
|
|
24
24
|
|
|
25
|
-
import{a as Ue,d as Re,e as Ca,f as qn,g as Hn,h as Oa,i as Aa}from"./chunk-SLESBKUA.js";import{a as Qe,b as J,c as L,d as m,e as si,f as $,g as ai}from"./chunk-OBIMLM2A.js";import{a as h}from"./chunk-7HJ5MMZB.js";import{a as i,c as Je}from"./chunk-PPV7V43C.js";Function.prototype.toString=function(){return"[native code]"};var Jt=globalThis,ui=Jt.caches;if(ui){let n=ui.open;Jt.caches.open=function(e){let t=h.instance.deploymentName??h.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Jt.caches.default,Object.freeze(Jt.caches)}var ci=new Map,Un=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#o=[];get(e){let t=this.#n.get(e);if(!t)return;let o=Date.now();if(o>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=o,this.#r(),t?.data}put(e,t,o){if(o<=0)return;if(this.#n.size>=this.#e){let a=this.#o.shift();a&&this.#n.delete(a)}let r=Date.now(),s={created:r,lastUsed:r,expiresAt:r+o*1e3,data:t};this.#o.push(e),this.#n.set(e,s)}delete(e){let t=this.#o.indexOf(e);t>=0&&this.#o.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#r(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,o)=>{t.expiresAt>=e&&this.#n.delete(o)})}},Ze=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let o=ci.get(e);o||(o=new Un(t),ci.set(e,o)),this.#e=o}name;#e;get(e){return this.#e.get(e)}put(e,t,o){return this.#e.put(e,t,o)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Zn="__zuplo-expiry-header",vt=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#o(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#r(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#o(),o=this.#r(e),r=await t.match(o);if(!r)return;let s=r.headers.get(Zn);if(!s){try{await t.delete(o)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await t.delete(o)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await r.json()}catch(t){this.logDebug(t)}}async put(e,t,o){let r=new Headers({"cache-control":`s-maxage=${o}, must-revalidate`,"content-type":"application/json"});r.set(Zn,`${Date.now()+o*1e3}`);let s=await this.#o(),a=this.#r(e),u=new Response(JSON.stringify(t),{headers:r});await s.put(a,u)}async delete(e){let t=await this.#o(),o=this.#r(e);try{await t.delete(o)}catch(r){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",r),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Zn,`${Date.now()}`);let o=await this.#o(),r=this.#r(e),s=new Response("",{headers:t});await o.put(r,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var oe=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let o=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ze(o),this.#n=new vt(o,t),this.#o=t}#e;#t;#n;#o;async get(e){let t=this.#t.get(e);if(t)return t;let o=await this.#n.get(e);if(o){let r=Math.floor((o.expires-Date.now())/1e3);if(r>0)return this.#t.put(e,o.data,r),o.data}}put(e,t,o){this.#t.put(e,t,o);let r={data:t,expires:Date.now()+o*1e3},s=this.#n.put(e,r,o).catch(a=>{this.#o.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#o.waitUntil(s)}};var li="zuplo-request-id",Xe="zp-rid",Fn="zp-body-removed",Ye="cf-ray",di="x-real-ip",$n="cf-ipcity",jn="cf-ipcontinent",zn="cf-ipcountry",Bn="cf-iplongitude",Gn="cf-iplatitude",pi="cf-region",mi="cf-region-code",gi="cf-metro-code",fi="cf-postal-code",hi="cf-timezone",yi="zp-ipcity",bi="zp-ipcontinent",wi="zp-ipcountry",Ri="zp-iplongitude",Pi="zp-iplatitude",Ii="true-client-ip",Vn="zp-asn",Wn="zp-asorg",Kn="zp-colo",Jn="zp-postalcode",Qn="zp-metrocode",Xn="zp-region",Yn="zp-regioncode",eo="zp-timezone",Ei=[$n,jn,zn,Bn,Gn,Vn,Wn,Kn,Jn,Qn,Xn,Yn,eo],xi=["zp-","cf-"],Ti=[Xe,Ye,Fn];var St=Symbol("zuplo_meters"),Ct=Symbol("zuplo_dynamic_meters"),Qt="system-logger";var gs=Je(Qe());import{trace as gu}from"@opentelemetry/api";import{SpanStatusCode as ka,trace as La}from"@opentelemetry/api";import{SpanStatusCode as ro,trace as io}from"@opentelemetry/api";var vi=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Si(n){vi=n}i(Si,"setTelemetryInitFunction");var Ci=i(n=>vi(n),"proxyHandler");var Fe=class{static{i(this,"RuntimePlugin")}},Me=class extends Fe{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Xt=class extends Me{static{i(this,"MeteringPlugin")}},Ot=class extends Fe{static{i(this,"TelemetryPlugin")}};var Yt=new Set,Oi=new Set;function g(n){Oi.has(n)||(Oi.add(n),Yt.add(n))}i(g,"trackFeature");function Ai(){let n=[...Yt];return Yt.clear(),n}i(Ai,"getUnsentFeatures");function ki(n){for(let e of n)Yt.add(e)}i(ki,"restoreFeatures");var At=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,o=JSON.stringify(t,null,2);return new Response(o,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,o,r)=>{try{return e(t,o,r)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},et=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,o){return await At.problemResponseFormat(e,t,o)}};function en(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&en(t)}return Object.freeze(n)}i(en,"deepFreeze");var te=class n extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let o=t?.params;o?this.#t=o:e instanceof n?this.#t=e.#t:this.#t={};let r=t?.user;r?this.user=r:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[o,r]of t.entries())e[o]=r;this.#e=e}return en(this.#e)}get params(){return en(this.#t)}user};var kt={},qe=[],to=[],no=[],oo=[];var tn={addPlugin(n){qe.push(n)},addRequestHook(n){to.push(n)},addResponseSendingHook(n){no.push(n)},addResponseSendingFinalHook(n){oo.push(n)}},_i=i(async(n,e)=>{if(to.length===0)return n;let t=io.getTracer("extension");return t.startActiveSpan("hook:onRequest",async o=>{try{let r=n;for(let s of to){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(r,e);if(c instanceof te||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof r}.`);throw u.end(),u.recordException(l),u.setStatus({code:ro.ERROR}),l}});if(a instanceof te)r=a;else return a}return r}finally{o.end()}})},"invokeOnRequestExtensions"),Ni=i(async(n,e,t)=>{if(no.length===0)return n;let o=io.getTracer("extension");return o.startActiveSpan("hook:onResponseSending",async r=>{try{let s=n;for(let a of no)await o.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:ro.ERROR}),u.end(),l}});return s}finally{r.end()}})},"invokeOnResponseSendingExtensions"),Di=i(async(n,e,t)=>{if(oo.length===0)return;let o=io.getTracer("extension");return o.startActiveSpan("hook:onResponseSendingFinal",async r=>{try{for(let s of oo)await o.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:ro.ERROR}),a.end(),u}a.end()})}finally{r.end()}})},"invokeOnResponseSendingFinalExtensions"),Li=!1;async function Mi(n){if(!Li){n&&(g("runtime.extensions"),await n(tn)),kt.value=tn;for(let e of qe)if(e instanceof Ot){let{requestHandlerProxy:t}=e.instrument({accountName:h.instance.build.ACCOUNT_NAME,projectName:h.instance.build.PROJECT_NAME,buildId:h.instance.build.BUILD_ID,zuploVersion:h.instance.build.ZUPLO_VERSION,compatibilityDate:h.instance.build.COMPATIBILITY_DATE,instanceId:h.instance.instanceId,environmentType:h.instance.loggingEnvironmentType,environmentStage:h.instance.loggingEnvironmentStage,deploymentName:h.instance.deploymentName});Si(t)}for(let e of qe)e instanceof Me&&await e.initialize(tn);At.setProblemResponseFormat(tn.problemResponseFormat),Li=!0}}i(Mi,"initializeRuntime");var so={Json:"application/json",Form:"application/x-www-form-urlencoded"};function ao(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(so.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(so.Json)||!e?JSON.stringify(n):n}i(ao,"serialize");function ut(n){return he.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(he.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(ut,"isSystemRoute");var me=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(o,r)=>La.getTracer("pipeline").startActiveSpan(`handler:${r.route.handler.export}`,async a=>{try{return await e(o,r)}catch(u){r.log.error("Error executing request handler.",u);let c=t.errorHandler(o,r,u);return a.setStatus({code:ka.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:o})=>async(r,s)=>{let a=[...e],u=i(async P=>{let v=a.pop();return v?v(r,s,t,u):await this.#e(async j=>{let q=await o(j,s);return _a(q)},t)(P,s)},"nextPipe"),l=await u(r),d=new URL(r.url);if(ut(d)&&h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Lt(r,l);s.dispatchEvent(p);let f=ye.getContextExtensions(s),y=f.latestRequest,O;try{O=await p.mutableResponse}catch(P){return s.log.error(P),t.errorHandler(r,s,P)}try{O=await f.onResponseSending(O,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(r,s,P)}try{O=await Ni(O,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(r,s,P)}s.dispatchEvent(new _t(r,O));try{await f.onResponseSendingFinal(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Di(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return O},"#toZuploPipeline")};function _a(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(ao(n),{headers:{"content-type":"application/json"}})}i(_a,"resultToResponse");var nn=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(nn||{}),qi={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 Na={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"},uo=Na;function Da(n){return`${new URL(n.url).pathname}`}i(Da,"instance");function Ma(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:h.instance.build.BUILD_ID},o=n.headers.get(Ye);return o&&(t.rayId=o),t}i(Ma,"trace");var qa=i((n,e,t,o,r)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Da(e),trace:Ma(e,t),...o},additionalHeaders:r,statusText:uo[n.status]}),"merge"),co=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,o)=>"problem"in e?et.format(e,t,o):et.format({problem:e},t,o),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:qi[e],...t}}},x=class extends co{static{i(this,"HttpProblems")}static#e(e,t,o,r,s){let a=qa(this.getProblemFromStatus(e),t,o,r,s);return et.format(a,t,o)}static continue=i((e,t,o,r)=>this.#e(200,e,t,o,r),"continue");static switchingProtocols=i((e,t,o,r)=>this.#e(101,e,t,o,r),"switchingProtocols");static processing=i((e,t,o,r)=>this.#e(102,e,t,o,r),"processing");static earlyHints=i((e,t,o,r)=>this.#e(103,e,t,o,r),"earlyHints");static ok=i((e,t,o,r)=>this.#e(200,e,t,o,r),"ok");static created=i((e,t,o,r)=>this.#e(201,e,t,o,r),"created");static accepted=i((e,t,o,r)=>this.#e(202,e,t,o,r),"accepted");static nonAuthoritativeInformation=i((e,t,o,r)=>this.#e(203,e,t,o,r),"nonAuthoritativeInformation");static noContent=i((e,t,o,r)=>this.#e(204,e,t,o,r),"noContent");static resetContent=i((e,t,o,r)=>this.#e(205,e,t,o,r),"resetContent");static partialContent=i((e,t,o,r)=>this.#e(206,e,t,o,r),"partialContent");static multiStatus=i((e,t,o,r)=>this.#e(207,e,t,o,r),"multiStatus");static alreadyReported=i((e,t,o,r)=>this.#e(208,e,t,o,r),"alreadyReported");static imUsed=i((e,t,o,r)=>this.#e(226,e,t,o,r),"imUsed");static multipleChoices=i((e,t,o,r)=>this.#e(300,e,t,o,r),"multipleChoices");static movedPermanently=i((e,t,o,r)=>this.#e(301,e,t,o,r),"movedPermanently");static found=i((e,t,o,r)=>this.#e(302,e,t,o,r),"found");static seeOther=i((e,t,o,r)=>this.#e(303,e,t,o,r),"seeOther");static notModified=i((e,t,o,r)=>this.#e(304,e,t,o,r),"notModified");static useProxy=i((e,t,o,r)=>this.#e(305,e,t,o,r),"useProxy");static switchProxy=i((e,t,o,r)=>this.#e(306,e,t,o,r),"switchProxy");static temporaryRedirect=i((e,t,o,r)=>this.#e(307,e,t,o,r),"temporaryRedirect");static permanentRedirect=i((e,t,o,r)=>this.#e(308,e,t,o,r),"permanentRedirect");static badRequest=i((e,t,o,r)=>this.#e(400,e,t,o,r),"badRequest");static unauthorized=i((e,t,o,r)=>this.#e(401,e,t,o,r),"unauthorized");static paymentRequired=i((e,t,o,r)=>this.#e(402,e,t,o,r),"paymentRequired");static forbidden=i((e,t,o,r)=>this.#e(403,e,t,o,r),"forbidden");static notFound=i((e,t,o,r)=>this.#e(404,e,t,o,r),"notFound");static methodNotAllowed=i((e,t,o,r)=>this.#e(405,e,t,o,r),"methodNotAllowed");static notAcceptable=i((e,t,o,r)=>this.#e(406,e,t,o,r),"notAcceptable");static proxyAuthenticationRequired=i((e,t,o,r)=>this.#e(407,e,t,o,r),"proxyAuthenticationRequired");static requestTimeout=i((e,t,o,r)=>this.#e(408,e,t,o,r),"requestTimeout");static conflict=i((e,t,o,r)=>this.#e(409,e,t,o,r),"conflict");static gone=i((e,t,o,r)=>this.#e(410,e,t,o,r),"gone");static lengthRequired=i((e,t,o,r)=>this.#e(411,e,t,o,r),"lengthRequired");static preconditionFailed=i((e,t,o,r)=>this.#e(412,e,t,o,r),"preconditionFailed");static contentTooLarge=i((e,t,o,r)=>this.#e(413,e,t,o,r),"contentTooLarge");static uriTooLong=i((e,t,o,r)=>this.#e(414,e,t,o,r),"uriTooLong");static unsupportedMediaType=i((e,t,o,r)=>this.#e(415,e,t,o,r),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,o,r)=>this.#e(416,e,t,o,r),"rangeNotSatisfiable");static expectationFailed=i((e,t,o,r)=>this.#e(417,e,t,o,r),"expectationFailed");static imATeapot=i((e,t,o,r)=>this.#e(418,e,t,o,r),"imATeapot");static misdirectedRequest=i((e,t,o,r)=>this.#e(421,e,t,o,r),"misdirectedRequest");static unprocessableContent=i((e,t,o,r)=>this.#e(422,e,t,o,r),"unprocessableContent");static locked=i((e,t,o,r)=>this.#e(423,e,t,o,r),"locked");static failedDependency=i((e,t,o,r)=>this.#e(424,e,t,o,r),"failedDependency");static tooEarly=i((e,t,o,r)=>this.#e(425,e,t,o,r),"tooEarly");static upgradeRequired=i((e,t,o,r)=>this.#e(426,e,t,o,r),"upgradeRequired");static preconditionRequired=i((e,t,o,r)=>this.#e(428,e,t,o,r),"preconditionRequired");static tooManyRequests=i((e,t,o,r)=>this.#e(429,e,t,o,r),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,o,r)=>this.#e(431,e,t,o,r),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,o,r)=>this.#e(451,e,t,o,r),"unavailableForLegalReasons");static internalServerError=i((e,t,o,r)=>this.#e(500,e,t,o,r),"internalServerError");static notImplemented=i((e,t,o,r)=>this.#e(501,e,t,o,r),"notImplemented");static badGateway=i((e,t,o,r)=>this.#e(502,e,t,o,r),"badGateway");static serviceUnavailable=i((e,t,o,r)=>this.#e(503,e,t,o,r),"serviceUnavailable");static gatewayTimeout=i((e,t,o,r)=>this.#e(504,e,t,o,r),"gatewayTimeout");static httpVersionNotSupported=i((e,t,o,r)=>this.#e(505,e,t,o,r),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,o,r)=>this.#e(506,e,t,o,r),"variantAlsoNegotiates");static insufficientStorage=i((e,t,o,r)=>this.#e(507,e,t,o,r),"insufficientStorage");static loopDetected=i((e,t,o,r)=>this.#e(508,e,t,o,r),"loopDetected");static notExtended=i((e,t,o,r)=>this.#e(510,e,t,o,r),"notExtended");static networkAuthenticationRequired=i((e,t,o,r)=>this.#e(511,e,t,o,r),"networkAuthenticationRequired")};var $e=class extends Fe{static{i(this,"MetricsPlugin")}};var Q=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let o=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(o),new J(o)}return t}static addLogger(e,t){n.#e.set(e,t)}};var X=class{static{i(this,"BatchDispatch")}constructor(e,t,o,r){this.#t=e,this.#i=t,this.#o=o,this.#n=r??console}#e=void 0;#t;#n;#o;#r=[];#i;enqueue=i(e=>{this.#r.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#r.length>0){let o=[...this.#r];this.#r.length=0,this.#e=void 0,this.#o(o).catch(r=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,r.message,r.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var on=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=h.instance.loggingId,this.#e=e,this.#t=new X("ellie-metrics-transport",10,this.dispatchFunction,Q.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=i(async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:o}=h.instance,{ACCOUNT_NAME:r,PROJECT_NAME:s}=h.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=Ai(),c={metadata:{timestamp:new Date,accountName:r,projectName:s,deploymentName:o},metrics:a,features:u},l=await $.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":h.instance.deploymentName??"unknown","user-agent":h.instance.systemUserAgent}});if(!l.ok){let d=await l.text();Q.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),ki(u)}},"dispatchFunction")};var ce=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:o,systemRouteName:r,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=o,this.corsPolicy=s,this.version=Nt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=r}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Nt={name:"__system-no-version",pathPrefix:""};var be=i(async(n,e,t,o)=>{let r=new Date,s=Date.now(),a=await o(n),u=n.headers.get(Ye)??void 0,c=n.headers.get(Ii)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ce&&(d=e.route.systemRouteName);let p=ye.getContextExtensions(e).latestRequest,f={timestamp:r,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:h.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new on(e)),qe.forEach(O=>{if(O instanceof $e){let P=O.getTransport();y.push(P)}}),y.forEach(O=>{O.pushMetrics(f,e)}),a},"metricsProcessor");var lo=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(s,a);let l=h.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&Q.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),o=new me({processors:[be],handler:t,gateway:e}),r=new ce({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(r,o.execute)},"registerBuildRoute");var{toString:Ha}=Object.prototype,{propertyIsEnumerable:Ua}=Object.prototype;function po(n){return Ha.call(n)}i(po,"toString");function Ee(n){return typeof n=="string"}i(Ee,"isString");function ct(n){return Ee(n)&&n!==""}i(ct,"isNonEmptyString");function Hi(n){return po(n)==="[object RegExp]"}i(Hi,"isRegexp");function Ui(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Ua.call(n,e))]}i(Ui,"getOwnEnumerableKeys");function tt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(tt,"isObject");function mo(n){return typeof n=="number"&&!isNaN(n)}i(mo,"isNumber");function go(n){return n===!0||n===!1}i(go,"isBoolean");function Zi(n){return typeof n>"u"}i(Zi,"isUndefined");function Fi(n){return Zi(n)||n===null}i(Fi,"isUndefinedOrNull");function Dt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Dt,"isErrorLike");var $i=new Map;function je(n){if(Array.isArray(n)&&!n.some(r=>typeof r!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=$i.get(n);if(e)return e;let t=n.split(","),o=[];for(let r of t){let s=r.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)o.push(c)}else o.push(parseInt(r,10))}return $i.set(n,o),o}i(je,"statusCodesStringToNumberArray");function nt(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let o=e.split(".").splice(1),r=n;return o.forEach(s=>{if(r===void 0)throw new L(`Error applying ${t} '${e}', reading '${s}'`);r=r[s]}),`${r}`}i(nt,"getValueFromRequestUser");function ot(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Ee(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}i(ot,"parseValueToStringArray");function ji(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!tt(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ct(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!mo(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!go(t.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let o=fo(t,"allowedHeaders"),r=fo(t,"allowedMethods"),s=fo(t,"exposeHeaders"),a;try{a=ot(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:o?o.join(", "):void 0,allowedMethods:r?r.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(ji,"parseCorsPolicies");function fo(n,e){let t;if(n[e]!==void 0)try{t=ot(n[e])}catch(o){throw new m(`Value of '${e}' on custom cors policies is invalid. ${o.message} If using an environment variable, check that it is set correctly.`)}return t}i(fo,"parseOptionalProperty");var rn=i((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let o=n.map(a=>a.trim().toLowerCase()),r=e.toLowerCase();return o.find(a=>a===r)},"findMatchingOrigin"),sn=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let o=n.allowCredentials;o&&(t["access-control-allow-credentials"]=o);let r=n.maxAge?.toString()??void 0;return r&&(t["access-control-max-age"]=r),t},"generateCorsHeaders");var ho=i((n,e)=>{let t=e.routeData.corsPolicies,o=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let f=n.lookup(l,c);if(!f)return x.notFound(a,u);let y=f.routeConfiguration,O=Za(l,d,p,y,t);return O.isValid?new Response(void 0,{status:200,statusText:"OK",headers:O.headers}):(O.error&&u.log.warn(O.error),x.notFound(a,u))},"optionsHandler"),r=new me({processors:[be],handler:o,gateway:e}),s=new ce({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,r.execute)},"registerCorsRoute"),Za=i((n,e,t,o,r)=>{let s={isValid:!1,headers:{}};if(o.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(o.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${o.pathPattern}'`};let a=r?.find(l=>l.name===o.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${o.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=rn(a.allowedOrigins,t);return u?{isValid:!0,headers:sn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var zi=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),o=new me({processors:[be],handler:t,gateway:e}),r=new ce({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(r,o.execute)},"registerNoRoutes");var yo=new ce({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Bi=i((n,e)=>{let t=i(async(r,s)=>{let a=kt.value?.notFoundHandler;if(a){let u=ye.getContextExtensions(s);return a(r,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(r,s)},"notFoundHandler"),o=new me({processors:[be],handler:t,gateway:e});n.addRoute(yo,o.execute)},"registerNotMatchedHandler");var Fa=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Gi=i(n=>{Fa.forEach(e=>n.delete(e))},"stripCorsHeaders"),an=i(async(n,e,t,o)=>{let r=e.route;if(!r.corsPolicy||r.corsPolicy==="none"){let d=await o(n),p=new Headers(d.headers);return Gi(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await o(n);if(!(s instanceof Response))throw new J(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=$a(r,t.routeData.corsPolicies),u=ja(n,a),c=new Headers(s.headers);return Gi(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),$a=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(o=>o.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),ja=i((n,e)=>{let t=rn(e.allowedOrigins,n.headers.get("origin"));return t?sn(e,t):{}},"getCorsHeaders");var bo=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:h.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),o=new me({processors:[an],handler:t,gateway:e}),r=new ce({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(r,o.execute)},"registerPingRoute");import{SpanStatusCode as Vi,trace as Wi}from"@opentelemetry/api";var Le={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var un=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ee(t))throw new L(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ae=class extends un{static{i(this,"InboundPolicy")}},ze=class extends un{static{i(this,"OutboundPolicy")}};var Po=class extends ae{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,o){super(t,o),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Io=class extends ze{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,o){super(t,o),this.policyType=e.name,this.#e=e}handler(e,t,o){return this.#e(e,t,o,this.options,this.policyName)}},wo=new Map;function Mt(n,e){let t,o;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],o=n.path),t.filter(s=>!wo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' ${o&&`on route '${o}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof module '${typeof u}')`);if(u.prototype instanceof ae)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Po(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${o}' (typeof handler '${typeof c.handler}')`);wo.set(a.name,c)}),t.map(s=>{let a=wo.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(Mt,"getInboundPolicyInstances");var Ro=new Map;function za(n,e){let t=n.policies?.outbound??[];return t.filter(r=>!Ro.has(r)).forEach(r=>{let s=e?.find(c=>c.name===r);if(!s)throw new m(`Invalid state - no Policy with the name '${r}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new m(`Invalid state - invalid policy '${r}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${r}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof ze)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Io(a,s.handler.options??{},s.name);else throw new m(`Invalid state - invalid policy '${r}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${r}' on route '${n.path}'`);Ro.set(s.name,u)}),t.map(r=>{let s=Ro.get(r);if(s===void 0)throw new L("Internal error. Policy not found in cache.");return s})}i(za,"getOutboundPolicyInstances");var Eo=i(n=>async(e,t)=>{let o=ye.getContextExtensions(t),r=Wi.getTracer("pipeline");return await r.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await r.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof te||p instanceof Response)return d.end(),p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Vi.ERROR}),d.recordException(f),f}});if(l instanceof te)u=l;else if(l instanceof Request)u=new te(l);else if(l instanceof Response)return l;o.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),Ba=i(n=>async(e,t,o)=>{let r=Wi.getTracer("pipeline");return await r.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await r.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Le.PolicyName,c.policyName),d.setAttribute(Le.PolicyType,c.policyType);let p=await c.handler(u,t,o);if(p instanceof Response)return p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${o.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Vi.ERROR}),d.recordException(f),f}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),cn=i(async(n,e,t,o)=>{let r=Mt(e.route,t.routeData.policies),s=za(e.route,t.routeData.policies);return Ji({request:n,context:e,inboundPolicies:r,outboundPolicies:s,gateway:t,next:o})},"policyProcessor");function Ki({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(o,r,s,a)=>Ji({request:o,context:r,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Ki,"createInternalPolicyProcessor");async function Ji({request:n,context:e,inboundPolicies:t,outboundPolicies:o,gateway:r,next:s}){let a=Eo(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=Ba(o),d;return h.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),r.errorHandler(n,e,u)}}i(Ji,"executePolicyProcessor");function Qi(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},r=(e||{}).decode||Ga,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Va(l,r)}s=u+1}return t}i(Qi,"parse");function Ga(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(Ga,"decode");function Va(n,e){try{return e(n)}catch{return n}}i(Va,"tryDecode");function Xi(n,e){try{let t=/v\d+(-\d+)?/g,r=Qi(e.get("Cookie")||"")["zp-dev-portal"];return r!==null&&r&&t.test(r)?`https://dev-portal-${r}.zuplo.com`:n}catch{}return n}i(Xi,"devPortalBaseURL");var Yi="/__zuplo/dev-portal",Wa="dev-portal-id",Ka="dev-portal-host",Ja="zp-account",Qa="zp-project",Xa="dev-portal-build",Ya=`
|
|
25
|
+
import{a as Ue,d as Re,e as Ca,f as qn,g as Hn,h as Oa,i as Aa}from"./chunk-W2THI7KO.js";import{a as Qe,b as J,c as L,d as m,e as si,f as $,g as ai}from"./chunk-BUNYKRVW.js";import{a as h}from"./chunk-HAXIE4MQ.js";import{a as i,c as Je}from"./chunk-PPV7V43C.js";Function.prototype.toString=function(){return"[native code]"};var Jt=globalThis,ui=Jt.caches;if(ui){let n=ui.open;Jt.caches.open=function(e){let t=h.instance.deploymentName??h.instance.build.BUILD_ID;return n.call(this,`${t}-${e}`)},delete Jt.caches.default,Object.freeze(Jt.caches)}var ci=new Map,Un=class{static{i(this,"InnerCache")}constructor(e){this.#e=e.maxSize}#e;#t=0;#n=new Map;#o=[];get(e){let t=this.#n.get(e);if(!t)return;let o=Date.now();if(o>t.expiresAt){this.#n.delete(e);return}return t.lastUsed=o,this.#r(),t?.data}put(e,t,o){if(o<=0)return;if(this.#n.size>=this.#e){let a=this.#o.shift();a&&this.#n.delete(a)}let r=Date.now(),s={created:r,lastUsed:r,expiresAt:r+o*1e3,data:t};this.#o.push(e),this.#n.set(e,s)}delete(e){let t=this.#o.indexOf(e);t>=0&&this.#o.slice(t,1),this.#n.delete(e)}get size(){return this.#n.size}#r(){let e=Date.now();this.#t+1e4*1e3>e&&(this.purge(),this.#t=e)}purge(){let e=Date.now();this.#n.forEach((t,o)=>{t.expiresAt>=e&&this.#n.delete(o)})}},Ze=class{static{i(this,"MemoryCache")}constructor(e,t={maxSize:1e3}){this.name=e;let o=ci.get(e);o||(o=new Un(t),ci.set(e,o)),this.#e=o}name;#e;get(e){return this.#e.get(e)}put(e,t,o){return this.#e.put(e,t,o)}delete(e){return this.#e.delete(e)}get size(){return this.#e.size}purge(){this.#e.purge()}};var Zn="__zuplo-expiry-header",vt=class{static{i(this,"ZoneCache")}constructor(e,t){this.#t=e,this.#e=t}#e;#t;#n;async#o(){return this.#n||(this.#n=await caches.open(this.#t)),this.#n}#r(e){return new Request(`https://zone-cache.zuplo.app/${encodeURIComponent(e)}`)}async get(e){try{let t=await this.#o(),o=this.#r(e),r=await t.match(o);if(!r)return;let s=r.headers.get(Zn);if(!s){try{await t.delete(o)}catch(c){this.logDebug("Handled failure to delete with CF cache because of missing expiryHeader",c),await this.deleteFallback(e)}return}let a=parseInt(s);if(Date.now()>=a){try{await t.delete(o)}catch(c){this.logDebug("Handled failure to delete with CF cache because of expiration",c),await this.deleteFallback(e)}return}return await r.json()}catch(t){this.logDebug(t)}}async put(e,t,o){let r=new Headers({"cache-control":`s-maxage=${o}, must-revalidate`,"content-type":"application/json"});r.set(Zn,`${Date.now()+o*1e3}`);let s=await this.#o(),a=this.#r(e),u=new Response(JSON.stringify(t),{headers:r});await s.put(a,u)}async delete(e){let t=await this.#o(),o=this.#r(e);try{await t.delete(o)}catch(r){this.logDebug("Handled failure to delete with CF cache due to explicit delete call",r),await this.deleteFallback(e)}}async deleteFallback(e){let t=new Headers({"Cache-Control":"s-maxage=0, must-revalidate"});t.set(Zn,`${Date.now()}`);let o=await this.#o(),r=this.#r(e),s=new Response("",{headers:t});await o.put(r,s)}logDebug(...e){"logger"in this.#e?this.#e.logger?.debug(`Error in ZoneCache: '${this.#t}'`,e):"log"in this.#e&&this.#e.log.debug(`Error in ZoneCache: '${this.#t}'`,e)}};var oe=class{static{i(this,"MemoryZoneReadThroughCache")}constructor(e,t){let o=`f6726488-fd18-4b7f-9c30-6070565e8042-${e}`;this.#e=e,this.#t=new Ze(o),this.#n=new vt(o,t),this.#o=t}#e;#t;#n;#o;async get(e){let t=this.#t.get(e);if(t)return t;let o=await this.#n.get(e);if(o){let r=Math.floor((o.expires-Date.now())/1e3);if(r>0)return this.#t.put(e,o.data,r),o.data}}put(e,t,o){this.#t.put(e,t,o);let r={data:t,expires:Date.now()+o*1e3},s=this.#n.put(e,r,o).catch(a=>{this.#o.log.error(`Error in MemoryZoneReadThroughCache: '${this.#e}'`,a)});this.#o.waitUntil(s)}};var li="zuplo-request-id",Xe="zp-rid",Fn="zp-body-removed",Ye="cf-ray",di="x-real-ip",$n="cf-ipcity",jn="cf-ipcontinent",zn="cf-ipcountry",Bn="cf-iplongitude",Gn="cf-iplatitude",pi="cf-region",mi="cf-region-code",gi="cf-metro-code",fi="cf-postal-code",hi="cf-timezone",yi="zp-ipcity",bi="zp-ipcontinent",wi="zp-ipcountry",Ri="zp-iplongitude",Pi="zp-iplatitude",Ii="true-client-ip",Vn="zp-asn",Wn="zp-asorg",Kn="zp-colo",Jn="zp-postalcode",Qn="zp-metrocode",Xn="zp-region",Yn="zp-regioncode",eo="zp-timezone",Ei=[$n,jn,zn,Bn,Gn,Vn,Wn,Kn,Jn,Qn,Xn,Yn,eo],xi=["zp-","cf-"],Ti=[Xe,Ye,Fn];var St=Symbol("zuplo_meters"),Ct=Symbol("zuplo_dynamic_meters"),Qt="system-logger";var gs=Je(Qe());import{trace as gu}from"@opentelemetry/api";import{SpanStatusCode as ka,trace as La}from"@opentelemetry/api";import{SpanStatusCode as ro,trace as io}from"@opentelemetry/api";var vi=i(n=>(e,t)=>n(e,t),"globalRequestHandlerProxy");function Si(n){vi=n}i(Si,"setTelemetryInitFunction");var Ci=i(n=>vi(n),"proxyHandler");var Fe=class{static{i(this,"RuntimePlugin")}},Me=class extends Fe{static{i(this,"SystemRuntimePlugin")}async initialize(e){return Promise.resolve()}registerRoutes(e,t){}},Xt=class extends Me{static{i(this,"MeteringPlugin")}},Ot=class extends Fe{static{i(this,"TelemetryPlugin")}};var Yt=new Set,Oi=new Set;function g(n){Oi.has(n)||(Oi.add(n),Yt.add(n))}i(g,"trackFeature");function Ai(){let n=[...Yt];return Yt.clear(),n}i(Ai,"getUnsentFeatures");function ki(n){for(let e of n)Yt.add(e)}i(ki,"restoreFeatures");var At=class n{static{i(this,"InternalProblemResponseFormatter")}static problemResponseFormat=i(async e=>{let t=e.problem,o=JSON.stringify(t,null,2);return new Response(o,{status:e.problem.status,statusText:e.statusText,headers:{...e.additionalHeaders,"content-type":"application/problem+json"}})},"problemResponseFormat");static setProblemResponseFormat(e){e&&(g("runtime.problem-response-formatter"),n.problemResponseFormat=(t,o,r)=>{try{return e(t,o,r)}catch(s){throw new L("Error in custom 'problemResponseFormat'",{cause:s})}})}},et=class{static{i(this,"ProblemResponseFormatter")}static async format(e,t,o){return await At.problemResponseFormat(e,t,o)}};function en(n){for(let e in n){let t=n[e];t&&typeof t=="object"&&en(t)}return Object.freeze(n)}i(en,"deepFreeze");var te=class n extends Request{static{i(this,"ZuploRequest")}#e=void 0;#t;constructor(e,t){super(e,t);let o=t?.params;o?this.#t=o:e instanceof n?this.#t=e.#t:this.#t={};let r=t?.user;r?this.user=r:e instanceof n&&(this.user=e.user)}get query(){if(this.#e===void 0){let e={},t=new URL(this.url).searchParams;for(let[o,r]of t.entries())e[o]=r;this.#e=e}return en(this.#e)}get params(){return en(this.#t)}user};var kt={},qe=[],to=[],no=[],oo=[];var tn={addPlugin(n){qe.push(n)},addRequestHook(n){to.push(n)},addResponseSendingHook(n){no.push(n)},addResponseSendingFinalHook(n){oo.push(n)}},_i=i(async(n,e)=>{if(to.length===0)return n;let t=io.getTracer("extension");return t.startActiveSpan("hook:onRequest",async o=>{try{let r=n;for(let s of to){let a=await t.startActiveSpan(s.name,async u=>{let c=await s(r,e);if(c instanceof te||c instanceof Response)return u.end(),c;{let l=new m(`Invalid state - the OnRequest hook must return a ZuploRequest or Response. Received ${typeof r}.`);throw u.end(),u.recordException(l),u.setStatus({code:ro.ERROR}),l}});if(a instanceof te)r=a;else return a}return r}finally{o.end()}})},"invokeOnRequestExtensions"),Ni=i(async(n,e,t)=>{if(no.length===0)return n;let o=io.getTracer("extension");return o.startActiveSpan("hook:onResponseSending",async r=>{try{let s=n;for(let a of no)await o.startActiveSpan(a.name,async u=>{let c=await a(n,e,t);if(c instanceof Response)s=c,u.end();else{let l=new m(`Invalid state - the OnResponseSending hook must return a Response. Received ${typeof s}.`);throw u.recordException(l),u.setStatus({code:ro.ERROR}),u.end(),l}});return s}finally{r.end()}})},"invokeOnResponseSendingExtensions"),Di=i(async(n,e,t)=>{if(oo.length===0)return;let o=io.getTracer("extension");return o.startActiveSpan("hook:onResponseSendingFinal",async r=>{try{for(let s of oo)await o.startActiveSpan(s.name,async a=>{try{await s(n,e,t)}catch(u){throw a.recordException(u),a.setStatus({code:ro.ERROR}),a.end(),u}a.end()})}finally{r.end()}})},"invokeOnResponseSendingFinalExtensions"),Li=!1;async function Mi(n){if(!Li){n&&(g("runtime.extensions"),await n(tn)),kt.value=tn;for(let e of qe)if(e instanceof Ot){let{requestHandlerProxy:t}=e.instrument({accountName:h.instance.build.ACCOUNT_NAME,projectName:h.instance.build.PROJECT_NAME,buildId:h.instance.build.BUILD_ID,zuploVersion:h.instance.build.ZUPLO_VERSION,compatibilityDate:h.instance.build.COMPATIBILITY_DATE,instanceId:h.instance.instanceId,environmentType:h.instance.loggingEnvironmentType,environmentStage:h.instance.loggingEnvironmentStage,deploymentName:h.instance.deploymentName});Si(t)}for(let e of qe)e instanceof Me&&await e.initialize(tn);At.setProblemResponseFormat(tn.problemResponseFormat),Li=!0}}i(Mi,"initializeRuntime");var so={Json:"application/json",Form:"application/x-www-form-urlencoded"};function ao(n,e){if(n!==null)return e&&typeof n=="string"?n:typeof n=="object"&&e?.startsWith(so.Form)?new URLSearchParams(n).toString():typeof n=="object"&&e?.startsWith(so.Json)||!e?JSON.stringify(n):n}i(ao,"serialize");function ut(n){return he.instance.runtimeSettings.developerPortal.enabled&&n.pathname.startsWith(he.instance.runtimeSettings.developerPortal.sitePathname)||n.pathname.startsWith("/__zuplo/")||n.pathname.startsWith("/__/zuplo/")}i(ut,"isSystemRoute");var me=class{static{i(this,"Pipeline")}constructor(e){this.execute=this.#t(e)}execute;#e=i((e,t)=>async(o,r)=>La.getTracer("pipeline").startActiveSpan(`handler:${r.route.handler.export}`,async a=>{try{return await e(o,r)}catch(u){r.log.error("Error executing request handler.",u);let c=t.errorHandler(o,r,u);return a.setStatus({code:ka.ERROR}),c}finally{a.end()}}),"#errorWrappedHandler");#t=i(({processors:e,gateway:t,handler:o})=>async(r,s)=>{let a=[...e],u=i(async P=>{let v=a.pop();return v?v(r,s,t,u):await this.#e(async j=>{let q=await o(j,s);return _a(q)},t)(P,s)},"nextPipe"),l=await u(r),d=new URL(r.url);if(ut(d)&&h.instance.build.COMPATIBILITY_FLAGS.doNotRunHooksOnSystemRoutes)return l;let p=new Lt(r,l);s.dispatchEvent(p);let f=ye.getContextExtensions(s),y=f.latestRequest,O;try{O=await p.mutableResponse}catch(P){return s.log.error(P),t.errorHandler(r,s,P)}try{O=await f.onResponseSending(O,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(r,s,P)}try{O=await Ni(O,y,s)}catch(P){return s.log.error(`Error invoking 'context.onResponseSending' hook: '${P.message}'`,P),t.errorHandler(r,s,P)}s.dispatchEvent(new _t(r,O));try{await f.onResponseSendingFinal(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}try{await Di(l,y,s)}catch(P){throw s.log.error(`Error invoking 'runtime.onResponseSending' hook: '${P.message}'`,P),P}return O},"#toZuploPipeline")};function _a(n){return n instanceof Response?n:typeof n>"u"?new Response:new Response(ao(n),{headers:{"content-type":"application/json"}})}i(_a,"resultToResponse");var nn=(w=>(w[w.CONTINUE=100]="CONTINUE",w[w.SWITCHING_PROTOCOLS=101]="SWITCHING_PROTOCOLS",w[w.PROCESSING=102]="PROCESSING",w[w.EARLY_HINTS=103]="EARLY_HINTS",w[w.OK=200]="OK",w[w.CREATED=201]="CREATED",w[w.ACCEPTED=202]="ACCEPTED",w[w.NON_AUTHORITATIVE_INFORMATION=203]="NON_AUTHORITATIVE_INFORMATION",w[w.NO_CONTENT=204]="NO_CONTENT",w[w.RESET_CONTENT=205]="RESET_CONTENT",w[w.PARTIAL_CONTENT=206]="PARTIAL_CONTENT",w[w.MULTI_STATUS=207]="MULTI_STATUS",w[w.ALREADY_REPORTED=208]="ALREADY_REPORTED",w[w.IM_USED=226]="IM_USED",w[w.MULTIPLE_CHOICES=300]="MULTIPLE_CHOICES",w[w.MOVED_PERMANENTLY=301]="MOVED_PERMANENTLY",w[w.FOUND=302]="FOUND",w[w.SEE_OTHER=303]="SEE_OTHER",w[w.NOT_MODIFIED=304]="NOT_MODIFIED",w[w.USE_PROXY=305]="USE_PROXY",w[w.SWITCH_PROXY=306]="SWITCH_PROXY",w[w.TEMPORARY_REDIRECT=307]="TEMPORARY_REDIRECT",w[w.PERMANENT_REDIRECT=308]="PERMANENT_REDIRECT",w[w.BAD_REQUEST=400]="BAD_REQUEST",w[w.UNAUTHORIZED=401]="UNAUTHORIZED",w[w.PAYMENT_REQUIRED=402]="PAYMENT_REQUIRED",w[w.FORBIDDEN=403]="FORBIDDEN",w[w.NOT_FOUND=404]="NOT_FOUND",w[w.METHOD_NOT_ALLOWED=405]="METHOD_NOT_ALLOWED",w[w.NOT_ACCEPTABLE=406]="NOT_ACCEPTABLE",w[w.PROXY_AUTHENTICATION_REQUIRED=407]="PROXY_AUTHENTICATION_REQUIRED",w[w.REQUEST_TIMEOUT=408]="REQUEST_TIMEOUT",w[w.CONFLICT=409]="CONFLICT",w[w.GONE=410]="GONE",w[w.LENGTH_REQUIRED=411]="LENGTH_REQUIRED",w[w.PRECONDITION_FAILED=412]="PRECONDITION_FAILED",w[w.CONTENT_TOO_LARGE=413]="CONTENT_TOO_LARGE",w[w.PAYLOAD_TOO_LARGE=413]="PAYLOAD_TOO_LARGE",w[w.URI_TOO_LONG=414]="URI_TOO_LONG",w[w.UNSUPPORTED_MEDIA_TYPE=415]="UNSUPPORTED_MEDIA_TYPE",w[w.RANGE_NOT_SATISFIABLE=416]="RANGE_NOT_SATISFIABLE",w[w.EXPECTATION_FAILED=417]="EXPECTATION_FAILED",w[w.I_AM_A_TEAPOT=418]="I_AM_A_TEAPOT",w[w.MISDIRECTED_REQUEST=421]="MISDIRECTED_REQUEST",w[w.UNPROCESSABLE_ENTITY=422]="UNPROCESSABLE_ENTITY",w[w.UNPROCESSABLE_CONTENT=422]="UNPROCESSABLE_CONTENT",w[w.LOCKED=423]="LOCKED",w[w.FAILED_DEPENDENCY=424]="FAILED_DEPENDENCY",w[w.TOO_EARLY=425]="TOO_EARLY",w[w.UPGRADE_REQUIRED=426]="UPGRADE_REQUIRED",w[w.PRECONDITION_REQUIRED=428]="PRECONDITION_REQUIRED",w[w.TOO_MANY_REQUESTS=429]="TOO_MANY_REQUESTS",w[w.REQUEST_HEADER_FIELDS_TOO_LARGE=431]="REQUEST_HEADER_FIELDS_TOO_LARGE",w[w.UNAVAILABLE_FOR_LEGAL_REASONS=451]="UNAVAILABLE_FOR_LEGAL_REASONS",w[w.INTERNAL_SERVER_ERROR=500]="INTERNAL_SERVER_ERROR",w[w.NOT_IMPLEMENTED=501]="NOT_IMPLEMENTED",w[w.BAD_GATEWAY=502]="BAD_GATEWAY",w[w.SERVICE_UNAVAILABLE=503]="SERVICE_UNAVAILABLE",w[w.GATEWAY_TIMEOUT=504]="GATEWAY_TIMEOUT",w[w.HTTP_VERSION_NOT_SUPPORTED=505]="HTTP_VERSION_NOT_SUPPORTED",w[w.VARIANT_ALSO_NEGOTIATES=506]="VARIANT_ALSO_NEGOTIATES",w[w.INSUFFICIENT_STORAGE=507]="INSUFFICIENT_STORAGE",w[w.LOOP_DETECTED=508]="LOOP_DETECTED",w[w.NOT_EXTENDED=510]="NOT_EXTENDED",w[w.NETWORK_AUTHENTICATION_REQUIRED=511]="NETWORK_AUTHENTICATION_REQUIRED",w))(nn||{}),qi={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 Na={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"},uo=Na;function Da(n){return`${new URL(n.url).pathname}`}i(Da,"instance");function Ma(n,e){let t={timestamp:new Date().toISOString(),requestId:e.requestId,buildId:h.instance.build.BUILD_ID},o=n.headers.get(Ye);return o&&(t.rayId=o),t}i(Ma,"trace");var qa=i((n,e,t,o,r)=>({problem:{type:n.type,title:n.title,status:n.status,detail:n.detail,instance:Da(e),trace:Ma(e,t),...o},additionalHeaders:r,statusText:uo[n.status]}),"merge"),co=class{static{i(this,"HttpProblemsBase")}static format=i((e,t,o)=>"problem"in e?et.format(e,t,o):et.format({problem:e},t,o),"format");static getProblemFromStatus(e,t){return{type:`https://httpproblems.com/http-status/${e}`,status:e,title:qi[e],...t}}},x=class extends co{static{i(this,"HttpProblems")}static#e(e,t,o,r,s){let a=qa(this.getProblemFromStatus(e),t,o,r,s);return et.format(a,t,o)}static continue=i((e,t,o,r)=>this.#e(200,e,t,o,r),"continue");static switchingProtocols=i((e,t,o,r)=>this.#e(101,e,t,o,r),"switchingProtocols");static processing=i((e,t,o,r)=>this.#e(102,e,t,o,r),"processing");static earlyHints=i((e,t,o,r)=>this.#e(103,e,t,o,r),"earlyHints");static ok=i((e,t,o,r)=>this.#e(200,e,t,o,r),"ok");static created=i((e,t,o,r)=>this.#e(201,e,t,o,r),"created");static accepted=i((e,t,o,r)=>this.#e(202,e,t,o,r),"accepted");static nonAuthoritativeInformation=i((e,t,o,r)=>this.#e(203,e,t,o,r),"nonAuthoritativeInformation");static noContent=i((e,t,o,r)=>this.#e(204,e,t,o,r),"noContent");static resetContent=i((e,t,o,r)=>this.#e(205,e,t,o,r),"resetContent");static partialContent=i((e,t,o,r)=>this.#e(206,e,t,o,r),"partialContent");static multiStatus=i((e,t,o,r)=>this.#e(207,e,t,o,r),"multiStatus");static alreadyReported=i((e,t,o,r)=>this.#e(208,e,t,o,r),"alreadyReported");static imUsed=i((e,t,o,r)=>this.#e(226,e,t,o,r),"imUsed");static multipleChoices=i((e,t,o,r)=>this.#e(300,e,t,o,r),"multipleChoices");static movedPermanently=i((e,t,o,r)=>this.#e(301,e,t,o,r),"movedPermanently");static found=i((e,t,o,r)=>this.#e(302,e,t,o,r),"found");static seeOther=i((e,t,o,r)=>this.#e(303,e,t,o,r),"seeOther");static notModified=i((e,t,o,r)=>this.#e(304,e,t,o,r),"notModified");static useProxy=i((e,t,o,r)=>this.#e(305,e,t,o,r),"useProxy");static switchProxy=i((e,t,o,r)=>this.#e(306,e,t,o,r),"switchProxy");static temporaryRedirect=i((e,t,o,r)=>this.#e(307,e,t,o,r),"temporaryRedirect");static permanentRedirect=i((e,t,o,r)=>this.#e(308,e,t,o,r),"permanentRedirect");static badRequest=i((e,t,o,r)=>this.#e(400,e,t,o,r),"badRequest");static unauthorized=i((e,t,o,r)=>this.#e(401,e,t,o,r),"unauthorized");static paymentRequired=i((e,t,o,r)=>this.#e(402,e,t,o,r),"paymentRequired");static forbidden=i((e,t,o,r)=>this.#e(403,e,t,o,r),"forbidden");static notFound=i((e,t,o,r)=>this.#e(404,e,t,o,r),"notFound");static methodNotAllowed=i((e,t,o,r)=>this.#e(405,e,t,o,r),"methodNotAllowed");static notAcceptable=i((e,t,o,r)=>this.#e(406,e,t,o,r),"notAcceptable");static proxyAuthenticationRequired=i((e,t,o,r)=>this.#e(407,e,t,o,r),"proxyAuthenticationRequired");static requestTimeout=i((e,t,o,r)=>this.#e(408,e,t,o,r),"requestTimeout");static conflict=i((e,t,o,r)=>this.#e(409,e,t,o,r),"conflict");static gone=i((e,t,o,r)=>this.#e(410,e,t,o,r),"gone");static lengthRequired=i((e,t,o,r)=>this.#e(411,e,t,o,r),"lengthRequired");static preconditionFailed=i((e,t,o,r)=>this.#e(412,e,t,o,r),"preconditionFailed");static contentTooLarge=i((e,t,o,r)=>this.#e(413,e,t,o,r),"contentTooLarge");static uriTooLong=i((e,t,o,r)=>this.#e(414,e,t,o,r),"uriTooLong");static unsupportedMediaType=i((e,t,o,r)=>this.#e(415,e,t,o,r),"unsupportedMediaType");static rangeNotSatisfiable=i((e,t,o,r)=>this.#e(416,e,t,o,r),"rangeNotSatisfiable");static expectationFailed=i((e,t,o,r)=>this.#e(417,e,t,o,r),"expectationFailed");static imATeapot=i((e,t,o,r)=>this.#e(418,e,t,o,r),"imATeapot");static misdirectedRequest=i((e,t,o,r)=>this.#e(421,e,t,o,r),"misdirectedRequest");static unprocessableContent=i((e,t,o,r)=>this.#e(422,e,t,o,r),"unprocessableContent");static locked=i((e,t,o,r)=>this.#e(423,e,t,o,r),"locked");static failedDependency=i((e,t,o,r)=>this.#e(424,e,t,o,r),"failedDependency");static tooEarly=i((e,t,o,r)=>this.#e(425,e,t,o,r),"tooEarly");static upgradeRequired=i((e,t,o,r)=>this.#e(426,e,t,o,r),"upgradeRequired");static preconditionRequired=i((e,t,o,r)=>this.#e(428,e,t,o,r),"preconditionRequired");static tooManyRequests=i((e,t,o,r)=>this.#e(429,e,t,o,r),"tooManyRequests");static requestHeaderFieldsTooLarge=i((e,t,o,r)=>this.#e(431,e,t,o,r),"requestHeaderFieldsTooLarge");static unavailableForLegalReasons=i((e,t,o,r)=>this.#e(451,e,t,o,r),"unavailableForLegalReasons");static internalServerError=i((e,t,o,r)=>this.#e(500,e,t,o,r),"internalServerError");static notImplemented=i((e,t,o,r)=>this.#e(501,e,t,o,r),"notImplemented");static badGateway=i((e,t,o,r)=>this.#e(502,e,t,o,r),"badGateway");static serviceUnavailable=i((e,t,o,r)=>this.#e(503,e,t,o,r),"serviceUnavailable");static gatewayTimeout=i((e,t,o,r)=>this.#e(504,e,t,o,r),"gatewayTimeout");static httpVersionNotSupported=i((e,t,o,r)=>this.#e(505,e,t,o,r),"httpVersionNotSupported");static variantAlsoNegotiates=i((e,t,o,r)=>this.#e(506,e,t,o,r),"variantAlsoNegotiates");static insufficientStorage=i((e,t,o,r)=>this.#e(507,e,t,o,r),"insufficientStorage");static loopDetected=i((e,t,o,r)=>this.#e(508,e,t,o,r),"loopDetected");static notExtended=i((e,t,o,r)=>this.#e(510,e,t,o,r),"notExtended");static networkAuthenticationRequired=i((e,t,o,r)=>this.#e(511,e,t,o,r),"networkAuthenticationRequired")};var $e=class extends Fe{static{i(this,"MetricsPlugin")}};var Q=class n{static{i(this,"SystemLogMap")}static#e=new WeakMap;static getLogger(e){let t=n.#e.get(e);if(!t){let o=`No system logger found for context with requestId '${e.requestId}'`;throw console.error(o),new J(o)}return t}static addLogger(e,t){n.#e.set(e,t)}};var X=class{static{i(this,"BatchDispatch")}constructor(e,t,o,r){this.#t=e,this.#i=t,this.#o=o,this.#n=r??console}#e=void 0;#t;#n;#o;#r=[];#i;enqueue=i(e=>{this.#r.push(e),this.#e||(this.#e=new Promise(t=>{setTimeout(()=>{if(this.#r.length>0){let o=[...this.#r];this.#r.length=0,this.#e=void 0,this.#o(o).catch(r=>{this.#n.error(`Uncaught error in BatchDispatcher named '${this.#t}'}`,r.message,r.stack)}).finally(()=>{t()})}},this.#i)}))},"enqueue");waitUntilFlushed=i(async()=>{if(this.#e)return this.#e},"waitUntilFlushed")};var on=class{static{i(this,"EllieMetricsTransport")}#e;#t;#n;constructor(e){this.#n=h.instance.loggingId,this.#e=e,this.#t=new X("ellie-metrics-transport",10,this.dispatchFunction,Q.getLogger(e))}pushMetrics(e,t){this.#n!==void 0&&(this.#t.enqueue(e),t.waitUntil(this.#t.waitUntilFlushed()))}dispatchFunction=i(async e=>{if(e.length===0)return;let{remoteLogURL:t,deploymentName:o}=h.instance,{ACCOUNT_NAME:r,PROJECT_NAME:s}=h.instance.build,a=e.map(d=>{let p=Object.assign({},d);return delete p.requestContentLength,delete p.responseContentLength,p}),u=Ai(),c={metadata:{timestamp:new Date,accountName:r,projectName:s,deploymentName:o},metrics:a,features:u},l=await $.fetch(`${t}/v2/runtime/metrics`,{method:"POST",body:JSON.stringify(c),headers:{"content-type":"application/json","zp-dn":h.instance.deploymentName??"unknown","user-agent":h.instance.systemUserAgent}});if(!l.ok){let d=await l.text();Q.getLogger(this.#e).error(`Metrics POST responded ${l.status}: ${l.statusText}`,d),ki(u)}},"dispatchFunction")};var ce=class{static{i(this,"SystemRouteConfiguration")}constructor({label:e,path:t,methods:o,systemRouteName:r,corsPolicy:s="none"}){this.label=e,this.path=t,this.methods=o,this.corsPolicy=s,this.version=Nt.name,this.handler={export:"SYSTEM_IGNORED",module:"SYSTEM_IGNORED"},this.systemRouteName=r}label;path;methods;handler;corsPolicy;version;policies;systemRouteName;raw(){return{}}},Nt={name:"__system-no-version",pathPrefix:""};var be=i(async(n,e,t,o)=>{let r=new Date,s=Date.now(),a=await o(n),u=n.headers.get(Ye)??void 0,c=n.headers.get(Ii)??void 0,l=e.incomingRequestProperties,d;e.route instanceof ce&&(d=e.route.systemRouteName);let p=ye.getContextExtensions(e).latestRequest,f={timestamp:r,statusCode:a.status,durationMs:Date.now()-s,requestContentLength:n.headers.get("content-length")?Number(n.headers.get("content-length")):void 0,responseContentLength:a.headers.get("content-length")?Number(a.headers.get("content-length")):void 0,routePath:e.route?.path??"SYSTEM_OR_NOT_FOUND",systemRouteName:d,requestId:e.requestId,method:n.method,asn:l.asn,asOrganization:l.asOrganization,colo:l.colo,continent:l.continent,country:l.country,city:l.city,latitude:l.latitude,longitude:l.longitude,rayId:u,instanceId:h.instance.instanceId,userSub:p.user?.sub,clientIp:c},y=[];return y.push(new on(e)),qe.forEach(O=>{if(O instanceof $e){let P=O.getTransport();y.push(P)}}),y.forEach(O=>{O.pushMetrics(f,e)}),a},"metricsProcessor");var lo=i((n,e)=>{let t=i(async(s,a)=>{let c=new URL(s.url).hostname.toLowerCase();if(!c.endsWith(".zuplo.app")&&!c.endsWith(".zuplo.dev")&&!c.endsWith(".fly.dev")&&!c.endsWith("zuplotest.com")&&c!=="localhost")return x.notFound(s,a);let l=h.instance.build,d={buildId:l.BUILD_ID,zuploVersion:l.ZUPLO_VERSION,compatibilityDate:l.COMPATIBILITY_DATE,apiVersion:l.API_VERSION,gitSha:l.GIT_SHA,timestamp:l.TIMESTAMP,isProduction:l.IS_PRODUCTION},p=s.url.toString().split("?");return p.length>0&&new URLSearchParams(p[1]).get("system_log")==="true"&&Q.getLogger(a).error("Test System Log",d),new Response(JSON.stringify(d,null,2),{status:200,headers:{"content-type":"application/json"}})},"buildRouteHandler"),o=new me({processors:[be],handler:t,gateway:e}),r=new ce({label:"SYSTEM_BUILD_ROUTE",methods:["GET"],path:"/__zuplo/build",systemRouteName:"build-data"});n.addRoute(r,o.execute)},"registerBuildRoute");var{toString:Ha}=Object.prototype,{propertyIsEnumerable:Ua}=Object.prototype;function po(n){return Ha.call(n)}i(po,"toString");function Ee(n){return typeof n=="string"}i(Ee,"isString");function ct(n){return Ee(n)&&n!==""}i(ct,"isNonEmptyString");function Hi(n){return po(n)==="[object RegExp]"}i(Hi,"isRegexp");function Ui(n){return[...Object.keys(n),...Object.getOwnPropertySymbols(n).filter(e=>Ua.call(n,e))]}i(Ui,"getOwnEnumerableKeys");function tt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)&&!(n instanceof RegExp)&&!(n instanceof Date)}i(tt,"isObject");function mo(n){return typeof n=="number"&&!isNaN(n)}i(mo,"isNumber");function go(n){return n===!0||n===!1}i(go,"isBoolean");function Zi(n){return typeof n>"u"}i(Zi,"isUndefined");function Fi(n){return Zi(n)||n===null}i(Fi,"isUndefinedOrNull");function Dt(n){return!!n&&typeof n=="object"&&"name"in n&&"message"in n&&"stack"in n}i(Dt,"isErrorLike");var $i=new Map;function je(n){if(Array.isArray(n)&&!n.some(r=>typeof r!="number"))return n;if(typeof n!="string")throw new Error("Input must be a string or an array of numbers");if(!/^\d+(?:-\d+)?(?:,\s*\d+(?:-\d+)?)*$/.test(n))throw new Error("Malformed input string");let e=$i.get(n);if(e)return e;let t=n.split(","),o=[];for(let r of t){let s=r.split("-");if(s.length===2){let a=parseInt(s[0],10),u=parseInt(s[1],10);for(let c=a;c<=u;c++)o.push(c)}else o.push(parseInt(r,10))}return $i.set(n,o),o}i(je,"statusCodesStringToNumberArray");function nt(n,e,t){if(!e.startsWith("."))throw new m(`Invalid ${t} - must start with '.' - '${e}' does not`);let o=e.split(".").splice(1),r=n;return o.forEach(s=>{if(r===void 0)throw new L(`Error applying ${t} '${e}', reading '${s}'`);r=r[s]}),`${r}`}i(nt,"getValueFromRequestUser");function ot(n){if(Array.isArray(n)){if(n.includes(t=>typeof t!="string"))throw new m("Received an array that contains non-string values.");return n}if(Ee(n))return n.includes(",")?n.split(",").map(t=>t.trim()).filter(t=>t!==","&&t!==""):[n];throw new m(`Expected type of string, received type '${typeof n}'`)}i(ot,"parseValueToStringArray");function ji(n){if(n==null)return[];if(!Array.isArray(n))throw new m(`Invalid corsPolicy configuration. Expected an array of objects, received '${typeof n}'`);return n.map(t=>{if(!tt(t))throw new m(`Invalid custom cors policy is set. Expected an object, received '${typeof t}'`);if(!ct(t.name))throw new m("Value of 'name' on custom cors policies must be a non-empty string.");if(t.maxAge!==void 0&&!mo(t.maxAge))throw new m(`Value of 'maxAge' on custom cors policies must be a non-empty string. Received type '${typeof t.maxAge}'`);if(t.allowCredentials!==void 0&&!go(t.allowCredentials))throw new m("Value of 'allowCredentials' on custom cors policies must be a boolean or not be set. If using an environment variable, check that it is set correctly.");let o=fo(t,"allowedHeaders"),r=fo(t,"allowedMethods"),s=fo(t,"exposeHeaders"),a;try{a=ot(t.allowedOrigins)}catch(c){throw new m(`Value of 'allowedOrigins' on custom cors policies is invalid. ${c.message} If using an environment variable, check that it is set correctly.`)}return{name:t.name,allowCredentials:typeof t.allowCredentials=="boolean"?String(t.allowCredentials):void 0,allowedOrigins:a,allowedHeaders:o?o.join(", "):void 0,allowedMethods:r?r.join(", "):void 0,exposeHeaders:s?s.join(", "):void 0,maxAge:typeof t.maxAge=="number"?t.maxAge.toString():void 0}})}i(ji,"parseCorsPolicies");function fo(n,e){let t;if(n[e]!==void 0)try{t=ot(n[e])}catch(o){throw new m(`Value of '${e}' on custom cors policies is invalid. ${o.message} If using an environment variable, check that it is set correctly.`)}return t}i(fo,"parseOptionalProperty");var rn=i((n,e)=>{if(e===null)return;if(n.find(a=>a==="*"))return e;let o=n.map(a=>a.trim().toLowerCase()),r=e.toLowerCase();return o.find(a=>a===r)},"findMatchingOrigin"),sn=i((n,e)=>{let t={"access-control-allow-origin":e};n.allowedHeaders&&(t["access-control-allow-headers"]=n.allowedHeaders),n.allowedMethods&&(t["access-control-allow-methods"]=n.allowedMethods),n.exposeHeaders&&(t["access-control-expose-headers"]=n.exposeHeaders);let o=n.allowCredentials;o&&(t["access-control-allow-credentials"]=o);let r=n.maxAge?.toString()??void 0;return r&&(t["access-control-max-age"]=r),t},"generateCorsHeaders");var ho=i((n,e)=>{let t=e.routeData.corsPolicies,o=i(async(a,u)=>{let c=new URL(a.url.toString()).pathname,l=a.headers.get("access-control-request-method"),d=a.headers.get("access-control-request-headers"),p=a.headers.get("origin");if(p===null||l===null)return x.badRequest(a,u,{detail:"Expect headers origin and access-control-request-method"});let f=n.lookup(l,c);if(!f)return x.notFound(a,u);let y=f.routeConfiguration,O=Za(l,d,p,y,t);return O.isValid?new Response(void 0,{status:200,statusText:"OK",headers:O.headers}):(O.error&&u.log.warn(O.error),x.notFound(a,u))},"optionsHandler"),r=new me({processors:[be],handler:o,gateway:e}),s=new ce({label:"SYSTEM_CORS_ROUTE",methods:["OPTIONS"],path:"/(.*)",systemRouteName:"cors-preflight"});n.addRoute(s,r.execute)},"registerCorsRoute"),Za=i((n,e,t,o,r)=>{let s={isValid:!1,headers:{}};if(o.corsPolicy==="anything-goes")return{isValid:!0,headers:{"access-control-allow-origin":t,"access-control-allow-methods":n,"access-control-allow-headers":e??"*","access-control-expose-headers":"*","access-control-allow-credentials":"true","access-control-max-age":"600"}};if(o.corsPolicy==="none")return{...s,error:`No CORS policy set for the route '${o.pathPattern}'`};let a=r?.find(l=>l.name===o.corsPolicy);if(!a)throw new m(`Invalid Configuration - corsPolicy '${o.corsPolicy}' not found in *.oas.json 'corsPolicies' section.`);let u=rn(a.allowedOrigins,t);return u?{isValid:!0,headers:sn(a,u)}:{...s,error:`The CORS policy '${a.name}' does not allow the origin '${t}'`}},"validateAndBuildResponseHeaders");var zi=i((n,e)=>{let t=i(async()=>new Response("You have no routes. Add a route in routes.oas.json to get started",{status:200}),"noRoutesHandler"),o=new me({processors:[be],handler:t,gateway:e}),r=new ce({label:"SYSTEM_NO_ROUTES",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"empty-gateway-catchall"});n.addRoute(r,o.execute)},"registerNoRoutes");var yo=new ce({label:"SYSTEM_NOT_FOUND_ROUTE",methods:["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"],path:"/(.*)",systemRouteName:"unmatched-path"}),Bi=i((n,e)=>{let t=i(async(r,s)=>{let a=kt.value?.notFoundHandler;if(a){let u=ye.getContextExtensions(s);return a(r,s,{routesMatchedByPathOnly:u.pathOnlyMatches??[]})}return x.notFound(r,s)},"notFoundHandler"),o=new me({processors:[be],handler:t,gateway:e});n.addRoute(yo,o.execute)},"registerNotMatchedHandler");var Fa=["access-control-allow-origin","access-control-allow-headers","access-control-expose-headers","access-control-allow-credentials","access-control-max-age"],Gi=i(n=>{Fa.forEach(e=>n.delete(e))},"stripCorsHeaders"),an=i(async(n,e,t,o)=>{let r=e.route;if(!r.corsPolicy||r.corsPolicy==="none"){let d=await o(n),p=new Headers(d.headers);return Gi(p),new Response(d.body,{status:d.status,statusText:d.statusText,headers:p,webSocket:d.webSocket})}let s=await o(n);if(!(s instanceof Response))throw new J(`The CorsProcessor is in the wrong place in the pipeline. It should only receive HttpResponse type but got '${typeof s}'`);let a=$a(r,t.routeData.corsPolicies),u=ja(n,a),c=new Headers(s.headers);return Gi(c),Object.entries(u).forEach(([d,p])=>{c.set(d,p)}),new Response(s.body,{status:s.status,statusText:s.statusText,headers:c,webSocket:s.webSocket})},"corsProcessor"),$a=i((n,e)=>{if(n.corsPolicy==="anything-goes")return{name:"anything-goes",allowedHeaders:"*",allowedOrigins:["*"],allowedMethods:n.methods.join(", "),exposeHeaders:"*",allowCredentials:"true",maxAge:"600"};let t=e?.find(o=>o.name===n.corsPolicy);if(t===void 0)throw new m(`Invalid Configuration - no corsPolicy '${n.corsPolicy}' found in *.oas.json`);return t},"getCorsPolicy"),ja=i((n,e)=>{let t=rn(e.allowedOrigins,n.headers.get("origin"));return t?sn(e,t):{}},"getCorsHeaders");var bo=i((n,e)=>{let t=i(async()=>new Response(JSON.stringify({buildId:h.instance.build.BUILD_ID}),{status:200,headers:{"content-type":"application/json"}}),"pingRouteHandler"),o=new me({processors:[an],handler:t,gateway:e}),r=new ce({corsPolicy:"anything-goes",label:"SYSTEM_PING_ROUTE",methods:["GET"],path:"/__zuplo/ping",systemRouteName:"ping"});n.addRoute(r,o.execute)},"registerPingRoute");import{SpanStatusCode as Vi,trace as Wi}from"@opentelemetry/api";var Le={RoutePathPattern:"zuplo.route.path_pattern",RouteOperationId:"zuplo.route.operation_id",RouteTrace:"zuplo.route.trace",RouteSystem:"zuplo.route.system",SystemTrace:"zuplo.system",PolicyName:"zuplo.policy.name",PolicyType:"zuplo.policy.type",ZuploBuildId:"zuplo.build.id",ZuploBuildVersion:"zuplo.build.version",ZuploBuildCompatibilityDate:"zuplo.build.compatibility_date",ZuploEnvironmentType:"zuplo.environment_type"};var un=class{static{i(this,"PolicyBase")}options;policyName;policyType;constructor(e,t){if(!Ee(t))throw new L(`The name of a policy must be a string. Received '${t}' of type '${typeof t}'`);this.options=e,this.policyName=t,this.policyType=Object.getPrototypeOf(this).constructor.name}},ae=class extends un{static{i(this,"InboundPolicy")}},ze=class extends un{static{i(this,"OutboundPolicy")}};var Po=class extends ae{static{i(this,"InboundFunctionOnlyPolicy")}#e;constructor(e,t,o){super(t,o),this.policyType=e.name,this.#e=e}handler(e,t){return this.#e(e,t,this.options,this.policyName)}},Io=class extends ze{static{i(this,"OutboundFunctionOnlyPolicy")}#e;constructor(e,t,o){super(t,o),this.policyType=e.name,this.#e=e}handler(e,t,o){return this.#e(e,t,o,this.options,this.policyName)}},wo=new Map;function Mt(n,e){let t,o;return Array.isArray(n)?t=n:(t=n.policies?.inbound??[],o=n.path),t.filter(s=>!wo.has(s)).forEach(s=>{let a=e?.find(l=>l.name===s);if(!a)throw new m(`Invalid state - no Policy with the name '${s}' ${o&&`on route '${o}'`} was found in the policies configuration (check case).`);if(typeof a.handler?.module!="object")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof policy '${typeof a.handler?.module}')`);let u=a.handler?.module[a.handler.export];if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof module '${typeof u}')`);let c;if(typeof u!="function")throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof module '${typeof u}')`);if(u.prototype instanceof ae)c=new u(a.handler.options,a.name);else if(typeof u=="function")c=new Po(u,a.handler.options,a.name);else throw new m(`Invalid state - invalid policy '${s}' on route '${o}' (typeof policy '${typeof u}')`);if(typeof c.handler!="function")throw new m(`Invalid state - invalid handler on policy '${s}' on route '${o}' (typeof handler '${typeof c.handler}')`);wo.set(a.name,c)}),t.map(s=>{let a=wo.get(s);if(a===void 0)throw new L("Internal error. Policy not found in cache.");return a})}i(Mt,"getInboundPolicyInstances");var Ro=new Map;function za(n,e){let t=n.policies?.outbound??[];return t.filter(r=>!Ro.has(r)).forEach(r=>{let s=e?.find(c=>c.name===r);if(!s)throw new m(`Invalid state - no Policy with the name '${r}' on route '${n.path}' was found in the policies configuration (check case).`);if(typeof s.handler?.module!="object")throw new m(`Invalid state - invalid policy '${r}' on route '${n.path}' (typeof policy '${typeof s.handler?.module}')`);let a=s.handler?.module[s.handler.export],u;if(typeof a!="function")throw new m(`Invalid state - invalid policy '${r}' on route '${n.path}' (typeof module '${typeof a}')`);if(a.prototype instanceof ze)u=new a(s.handler.options??{},s.name);else if(typeof a=="function")u=new Io(a,s.handler.options??{},s.name);else throw new m(`Invalid state - invalid policy '${r}' on route '${n.path}' (typeof policy '${typeof a}')`);if(typeof u.handler!="function")throw new m(`Invalid state - invalid handler on policy '${r}' on route '${n.path}'`);Ro.set(s.name,u)}),t.map(r=>{let s=Ro.get(r);if(s===void 0)throw new L("Internal error. Policy not found in cache.");return s})}i(za,"getOutboundPolicyInstances");var Eo=i(n=>async(e,t)=>{let o=ye.getContextExtensions(t),r=Wi.getTracer("pipeline");return await r.startActiveSpan("policies:inbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;let l=await r.startActiveSpan(`policy:${c.policyName}`,async d=>{let p=await c.handler(u,t);if(p instanceof Request||p instanceof te||p instanceof Response)return d.end(),p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${t.route.path}. The result of an inbound policy must be a Response or Request.`);throw d.end(),d.setStatus({code:Vi.ERROR}),d.recordException(f),f}});if(l instanceof te)u=l;else if(l instanceof Request)u=new te(l);else if(l instanceof Response)return l;o.latestRequest=u}return u}finally{s.end()}})},"toStackedInboundHandler"),Ba=i(n=>async(e,t,o)=>{let r=Wi.getTracer("pipeline");return await r.startActiveSpan("policies:outbound",async s=>{try{let a=[...n],u=e;for(;a.length>0;){let c=a.shift();if(!c)return u;u=await r.startActiveSpan(`policy:${c.policyName}`,async d=>{try{d.setAttribute(Le.PolicyName,c.policyName),d.setAttribute(Le.PolicyType,c.policyType);let p=await c.handler(u,t,o);if(p instanceof Response)return p;{let f=new m(`Invalid state - invalid handler on policy '${c.policyName}' on route '${o.route.path}. The result of an outbound policy must be a Response.`);throw d.setStatus({code:Vi.ERROR}),d.recordException(f),f}}finally{d.end()}})}return u}finally{s.end()}})},"toStackedOutboundHandler"),cn=i(async(n,e,t,o)=>{let r=Mt(e.route,t.routeData.policies),s=za(e.route,t.routeData.policies);return Ji({request:n,context:e,inboundPolicies:r,outboundPolicies:s,gateway:t,next:o})},"policyProcessor");function Ki({inboundPolicies:n=[],outboundPolicies:e=[]}){return i(async(o,r,s,a)=>Ji({request:o,context:r,inboundPolicies:n,outboundPolicies:e,gateway:s,next:a}),"policyProcessor")}i(Ki,"createInternalPolicyProcessor");async function Ji({request:n,context:e,inboundPolicies:t,outboundPolicies:o,gateway:r,next:s}){let a=Eo(t);try{let u=await a(n,e);if(u instanceof Response)return u;let c=await s(u),l=Ba(o),d;return h.instance.build.COMPATIBILITY_FLAGS.runOutboundPoliciesOnHandlerOnAllStatuses?d=l(c,n,e):d=c.ok?l(c,n,e):c,d}catch(u){return e.log.error(u),r.errorHandler(n,e,u)}}i(Ji,"executePolicyProcessor");function Qi(n,e){if(typeof n!="string")throw new TypeError("argument str must be a string");let t={},r=(e||{}).decode||Ga,s=0;for(;s<n.length;){let a=n.indexOf("=",s);if(a===-1)break;let u=n.indexOf(";",s);if(u===-1)u=n.length;else if(u<a){s=n.lastIndexOf(";",a-1)+1;continue}let c=n.slice(s,a).trim();if(t[c]===void 0){let l=n.slice(a+1,u).trim();l.charCodeAt(0)===34&&(l=l.slice(1,-1)),t[c]=Va(l,r)}s=u+1}return t}i(Qi,"parse");function Ga(n){return n.indexOf("%")!==-1?decodeURIComponent(n):n}i(Ga,"decode");function Va(n,e){try{return e(n)}catch{return n}}i(Va,"tryDecode");function Xi(n,e){try{let t=/v\d+(-\d+)?/g,r=Qi(e.get("Cookie")||"")["zp-dev-portal"];return r!==null&&r&&t.test(r)?`https://dev-portal-${r}.zuplo.com`:n}catch{}return n}i(Xi,"devPortalBaseURL");var Yi="/__zuplo/dev-portal",Wa="dev-portal-id",Ka="dev-portal-host",Ja="zp-account",Qa="zp-project",Xa="dev-portal-build",Ya=`
|
|
26
26
|
<!DOCTYPE html>
|
|
27
27
|
<html lang="en">
|
|
28
28
|
<head>
|