@zuplo/runtime 6.38.13 → 6.38.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/out/esm/index.js CHANGED
@@ -83,5 +83,5 @@ Signature verification is impossible without access to the original signed mater
83
83
  `&&b[T]!=="\r";T++)_+=b[T];if(_=_.trim(),_[_.length-1]==="/"&&(_=_.substring(0,_.length-1),T--),!J(_)){let $;return _.trim().length===0?$="Invalid space after '<'.":$="Tag '"+_+"' is an invalid name.",M("InvalidTag",$,X(b,T))}let D=U(b,T);if(D===!1)return M("InvalidAttr","Attributes for '"+_+"' have open quote.",X(b,T));let ee=D.value;if(T=D.index,ee[ee.length-1]==="/"){let $=T-ee.length;ee=ee.substring(0,ee.length-1);let q=j(ee,O);if(q===!0)me=!0;else return M(q.err.code,q.err.msg,X(b,$+q.err.line))}else if(B)if(D.tagClosed){if(ee.trim().length>0)return M("InvalidTag","Closing tag '"+_+"' can't have attributes or invalid starting.",X(b,L));{let $=G.pop();if(_!==$.tagName){let q=X(b,$.tagStartPos);return M("InvalidTag","Expected closing tag '"+$.tagName+"' (opened in line "+q.line+", col "+q.col+") instead of closing tag '"+_+"'.",X(b,L))}G.length==0&&(P=!0)}}else return M("InvalidTag","Closing tag '"+_+"' doesn't have proper closing.",X(b,T));else{let $=j(ee,O);if($!==!0)return M($.err.code,$.err.msg,X(b,T-ee.length+$.err.line));if(P===!0)return M("InvalidXml","Multiple possible root nodes found.",X(b,T));O.unpairedTags.indexOf(_)!==-1||G.push({tagName:_,tagStartPos:L}),me=!0}for(T++;T<b.length;T++)if(b[T]==="<")if(b[T+1]==="!"){T++,T=z(b,T);continue}else if(b[T+1]==="?"){if(T=F(b,++T),T.err)return T}else break;else if(b[T]==="&"){let $=I(b,T);if($==-1)return M("InvalidChar","char '&' is not expected.",X(b,T));T=$}else if(P===!0&&!S(b[T]))return M("InvalidXml","Extra text at the end",X(b,T));b[T]==="<"&&T--}}else{if(S(b[T]))continue;return M("InvalidChar","char '"+b[T]+"' is not expected.",X(b,T))}if(me){if(G.length==1)return M("InvalidTag","Unclosed tag '"+G[0].tagName+"'.",X(b,G[0].tagStartPos));if(G.length>0)return M("InvalidXml","Invalid '"+JSON.stringify(G.map(T=>T.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1})}else return M("InvalidXml","Start tag expected.",1);return!0};function S(b){return b===" "||b===" "||b===`
84
84
  `||b==="\r"}i(S,"isWhiteSpace"),r(S,"isWhiteSpace");function F(b,O){let G=O;for(;O<b.length;O++)if(b[O]=="?"||b[O]==" "){let me=b.substr(G,O-G);if(O>5&&me==="xml")return M("InvalidXml","XML declaration allowed only at the start of the document.",X(b,O));if(b[O]=="?"&&b[O+1]==">"){O++;break}else continue}return O}i(F,"readPI"),r(F,"readPI");function z(b,O){if(b.length>O+5&&b[O+1]==="-"&&b[O+2]==="-"){for(O+=3;O<b.length;O++)if(b[O]==="-"&&b[O+1]==="-"&&b[O+2]===">"){O+=2;break}}else if(b.length>O+8&&b[O+1]==="D"&&b[O+2]==="O"&&b[O+3]==="C"&&b[O+4]==="T"&&b[O+5]==="Y"&&b[O+6]==="P"&&b[O+7]==="E"){let G=1;for(O+=8;O<b.length;O++)if(b[O]==="<")G++;else if(b[O]===">"&&(G--,G===0))break}else if(b.length>O+9&&b[O+1]==="["&&b[O+2]==="C"&&b[O+3]==="D"&&b[O+4]==="A"&&b[O+5]==="T"&&b[O+6]==="A"&&b[O+7]==="["){for(O+=8;O<b.length;O++)if(b[O]==="]"&&b[O+1]==="]"&&b[O+2]===">"){O+=2;break}}return O}i(z,"readCommentAndCDATA"),r(z,"readCommentAndCDATA");var Z='"',C="'";function U(b,O){let G="",me="",P=!1;for(;O<b.length;O++){if(b[O]===Z||b[O]===C)me===""?me=b[O]:me!==b[O]||(me="");else if(b[O]===">"&&me===""){P=!0;break}G+=b[O]}return me!==""?!1:{value:G,index:O,tagClosed:P}}i(U,"readAttributeStr"),r(U,"readAttributeStr");var V=new RegExp(`(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['"])(([\\s\\S])*?)\\5)?`,"g");function j(b,O){let G=A.getAllMatches(b,V),me={};for(let P=0;P<G.length;P++){if(G[P][1].length===0)return M("InvalidAttr","Attribute '"+G[P][2]+"' has no space in starting.",Ce(G[P]));if(G[P][3]!==void 0&&G[P][4]===void 0)return M("InvalidAttr","Attribute '"+G[P][2]+"' is without value.",Ce(G[P]));if(G[P][3]===void 0&&!O.allowBooleanAttributes)return M("InvalidAttr","boolean attribute '"+G[P][2]+"' is not allowed.",Ce(G[P]));let T=G[P][2];if(!le(T))return M("InvalidAttr","Attribute '"+T+"' is an invalid name.",Ce(G[P]));if(!me.hasOwnProperty(T))me[T]=1;else return M("InvalidAttr","Attribute '"+T+"' is repeated.",Ce(G[P]))}return!0}i(j,"validateAttributeString"),r(j,"validateAttributeString");function x(b,O){let G=/\d/;for(b[O]==="x"&&(O++,G=/[\da-fA-F]/);O<b.length;O++){if(b[O]===";")return O;if(!b[O].match(G))break}return-1}i(x,"validateNumberAmpersand"),r(x,"validateNumberAmpersand");function I(b,O){if(O++,b[O]===";")return-1;if(b[O]==="#")return O++,x(b,O);let G=0;for(;O<b.length;O++,G++)if(!(b[O].match(/\w/)&&G<20)){if(b[O]===";")break;return-1}return O}i(I,"validateAmpersand"),r(I,"validateAmpersand");function M(b,O,G){return{err:{code:b,msg:O,line:G.line||G,col:G.col}}}i(M,"getErrorObject"),r(M,"getErrorObject");function le(b){return A.isName(b)}i(le,"validateAttrName"),r(le,"validateAttrName");function J(b){return A.isName(b)}i(J,"validateTagName"),r(J,"validateTagName");function X(b,O){let G=b.substring(0,O).split(/\r?\n/);return{line:G.length,col:G[G.length-1].length+1}}i(X,"getLineNumberForPosition"),r(X,"getLineNumberForPosition");function Ce(b){return b.startIndex+b[1].length}i(Ce,"getPositionFromMatch"),r(Ce,"getPositionFromMatch")}}),y=o({"node_modules/fast-xml-parser/src/xmlparser/XMLParser.js"(R,A){var{buildOptions:N}=s(),S=d(),{prettify:F}=p(),z=f(),Z=class{static{i(this,"XMLParser")}static{r(this,"XMLParser")}constructor(C){this.externalEntities={},this.options=N(C)}parse(C,U){if(typeof C!="string")if(C.toString)C=C.toString();else throw new Error("XML data is accepted in String or Bytes[] form.");if(U){U===!0&&(U={});let x=z.validate(C,U);if(x!==!0)throw Error(`${x.err.msg}:${x.err.line}:${x.err.col}`)}let V=new S(this.options);V.addExternalEntities(this.externalEntities);let j=V.parseXml(C);return this.options.preserveOrder||j===void 0?j:F(j,this.options)}addEntity(C,U){if(U.indexOf("&")!==-1)throw new Error("Entity value can't have '&'");if(C.indexOf("&")!==-1||C.indexOf(";")!==-1)throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if(U==="&")throw new Error("An entity with value '&' is not permitted");this.externalEntities[C]=U}};A.exports=Z}});let v=y();return new v(n)},"getXmlParser");var Ii=class extends Je{static{i(this,"XmlToJsonOutboundPolicy")}parser;parseOnStatusCodes;constructor(e,t){super(e,t),g("policy.outbound.xml-to-json"),W(this.options,this.policyName).optional("removeNSPrefix","boolean").optional("ignoreProcessingInstructions","boolean").optional("ignoreDeclarations","boolean").optional("ignoreAttributes","boolean").optional("stopNodes","array").optional("attributeNamePrefix","string").optional("textNodeName","string").optional("trimValues","boolean"),this.parseOnStatusCodes=e.parseOnStatusCodes?Ve(e.parseOnStatusCodes):void 0,this.parser=uu({removeNSPrefix:e?.removeNSPrefix??!0,ignorePiTags:e?.ignoreProcessingInstructions??!0,ignoreDeclaration:e?.ignoreDeclarations??!0,ignoreAttributes:e?.ignoreAttributes??!0,stopNodes:e?.stopNodes??[],attributeNamePrefix:e?.attributeNamePrefix??"@_",textNodeName:e?.textNodeName??"#text",trimValues:e?.trimValues??!0})}async handler(e,t,r){if(this.parseOnStatusCodes&&!this.parseOnStatusCodes.includes(e.status))return e;let o;try{let u=await e.text();o=this.parser.parse(u)}catch(u){let c=`XmlToJsonOutboundPolicy - Error parsing XML contents in policy '${this.policyName}'.`;throw r.log.error(c,u),new k(c)}let s=new Headers(e.headers);return s.set("content-type","application/json"),new Response(JSON.stringify(o),{status:e.status,statusText:e.statusText,headers:s})}};var Ei=class{static{i(this,"ServiceProviderImpl")}services=new Map;addService(e,t){if(this.services.get(e))throw new K(`A service with the name ${e} already exists -- you cannot have duplicate services`);this.services.set(e,t)}getService(e){return this.services.get(e)}};var nn=class{static{i(this,"BackgroundDispatcher")}#e;constructor(e,t){if(!t||t.msDelay===void 0)throw new m("BackgroundDispatcher: options.msDelay is required");this.#e=new Y(t.name??"",t.msDelay,e)}enqueue=i(e=>{this.#e.enqueue(e),Ke().waitUntil(this.#e.waitUntilFlushed())},"enqueue")};var cu=10,lu=3e4,rn=class{static{i(this,"BackgroundLoader")}#e=new Map;#t;#n;#r;#o;#i={};constructor(e,t){if(typeof t=="number"){let r=t;this.#n=r*1e3,this.#o=lu,this.#r=cu}else{let r=t;this.#n=r.ttlSeconds*1e3,this.#o=r.loaderTimeoutSeconds?r.loaderTimeoutSeconds*1e3:lu,this.#r=cu}this.#t=e}#s(e){return e.expiry<=new Date}#a(e){let t=this.#i[e];return!(t===void 0||t===0)}#u(e){let t=this.#e.get(e);if(t&&!this.#s(t))return t.data}async get(e){let t=this.#u(e);if(t)return this.#l(e),t;if(this.#a(e))try{await ap(()=>this.#u(e)!==void 0||!this.#a,this.#o+this.#r+1,this.#r);let r=this.#u(e);if(r)return r}catch{}return this.#c(e)}#l(e){if(!this.#a(e)){let t=this.#c(e);Ke().waitUntil(t)}}async#c(e){try{this.#i[e]===void 0&&(this.#i[e]=0),this.#i[e]++;let t=await Promise.race([this.#t(e),scheduler.wait(this.#o)]);if(t===void 0)throw new m(`BackgroundLoader: Loader timed out after ${this.#o} ms.`);return this.#e.set(e,{data:t,expiry:new Date(Date.now()+this.#n)}),t}finally{this.#i[e]--}}};async function ap(n,e,t){let r=Date.now();for(;!n();){let o=Date.now()-r;if(o>e)throw new m(`BackgroundLoader: Timeout waiting for an on-going loader after ${o} ms.`);await scheduler.wait(t)}}i(ap,"waitUntilTrue");var xi,qe=class{static{i(this,"RequestLoggerCore")}constructor(e,t){let o=(e.batchPeriodSeconds??.01)*1e3;this.#n=new nn(this.#t,{msDelay:o}),this.#e=e,this.initialize(t)}initialize(e){e.addRequestHook((t,r)=>{xi=r;let o=Date.now();return r.addResponseSendingFinalHook(async s=>{let a={deploymentName:h.instance.deploymentName??"",instanceId:h.instance.instanceId,systemUserAgent:h.instance.systemUserAgent,requestStartTime:new Date(o),durationMs:Date.now()-o},u=await this.#e.generateLogEntry(s,t,r,a);this.#n.enqueue(u)}),t})}#e;#t=i(async e=>{if(e.length!==0)try{await this.#e.dispatchFunction(e)}catch(t){up(t,this.#e.name)}},"#dispatch");#n};function up(n,e){if(!xi){let r=Ke(),o=ne({level:"error",messages:[`RequestLoggerCore '${e}': No context available to log user errors`]});r.waitUntil(o);return}let t;n instanceof Error?t={message:n.message,status:-1,details:n.stack??""}:t=n,xi.log.error(`RequestLoggerCore '${e}': Error dispatching log entries.`,t)}i(up,"logError");var du="plugin.azure-blob-request-logger",cp=i(()=>`${new Date().toISOString().replace(/[:-]/g,"-").replace("T","-").split(".")[0]}-${h.instance.instanceId}.csv`,"defaultGenerateBlobName"),pu,vi=class extends ye{static{i(this,"AzureBlobPlugin")}constructor(e){super(),this.#e=e,g(du)}async initialize(e){new qe({name:du,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=i(async e=>{if(e.length===0)return;let t=lp(e[0]),r=pp(e,t),s=(this.#e.generateBlobName??cp)(e);await mp(r,this.#e,s)},"#dispatch")};function lp(n){return Object.keys(n)}i(lp,"getHeaders");function dp(n){if(n==null)return"";let e=String(n);return(e.includes('"')||e.includes(",")||e.includes(`
85
85
  `)||e.includes("\r"))&&(e=e.replace(/"/g,'""'),e=`"${e}"`),e}i(dp,"escapeCsvValue");function pp(n,e){let t=[];t.push(e.join(","));for(let r of n){let o=[];for(let s of e){let a=r[s];o.push(dp(a))}t.push(o.join(","))}return t.join(`
86
- `)}i(pp,"generateCsvContent");async function mp(n,e,t){let{sasUrl:r}=e,o=r.split("?"),s=`${o[0]}/${t}?${o[1]}`;try{let a=await H.fetch(s,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/csv"},body:n});a.ok||(Ti({message:a.statusText,status:a.status,details:await a.text()}),Ti({message:a.statusText,status:a.status,details:await a.text()}))}catch(a){Ti(a)}}i(mp,"uploadToAzureBlobStorage");function Ti(n){if(!pu){let t=Ke(),r=ne({level:"error",messages:["AzureBlobCsvPlugin: No context available to log user errors"]});t.waitUntil(r);return}let e;n instanceof Error?e={message:n.message,status:-1,details:n.stack??""}:e=n,pu.log.error("AzureBlobCsvPlugin: Error uploading to Azure Blob Storage",e)}i(Ti,"logError");function Gn(n,e,t){return new Promise((r,o)=>{let s=setTimeout(()=>{o(new Error(t||`Operation timed out after ${e} second(s)`))},e*1e3);n.then(a=>{clearTimeout(s),r(a)}).catch(a=>{clearTimeout(s),o(a)})})}i(Gn,"withTimeout");async function gp(n,e,t,r){let o;for(let s=0;s<t;s++)try{let a=fetch(n,e),u=r?await Gn(a,r,"Fetch timed out"):await a;if(u.ok)return u;o=new Error(`Fetch returned status ${u.status}`)}catch(a){o=a}throw o||new Error("Fetch failed without a response.")}i(gp,"fetchWithRetry");async function fp(n,e,t,r,o){let s;for(let a=0;a<r;a++)try{let u=new Headers(e.headers||{});u.set("Authorization",`Bearer ${t}`);let c={...e,headers:u},l=fetch(n,c),d=o?await Gn(l,o,"Fetch timed out"):await l;if(d.status===401||d.ok)return d;s=new Error(`Fetch returned status ${d.status}`)}catch(u){s=u}throw s||new Error("Fetch with token failed without a response.")}i(fp,"fetchWithToken");async function on(n,e={}){let{retries:t=3,timeoutSeconds:r,auth:o,...s}=e;if(!o)return await gp(n,s,t,r);let a=o.retries??3,u=o.timeoutSeconds,c;for(let l=0;l<a;l++)try{let d=o.callback();if(c=u?await Gn(d,u,"Auth token acquisition timed out"):await d,c)break}catch(d){if(l===a-1)throw d}if(!c)throw new Error("Failed to acquire token after maximum retries.");for(let l=0;l<a;l++){let d=await fp(n,s,c,t,r);if(d.status!==401)return d;for(let p=0;p<a;p++)try{let f=o.callback();if(c=u?await Gn(f,u,"Auth token acquisition timed out"):await f,c)break}catch(f){if(p===a-1)throw f}if(!c)throw new Error("Failed to refresh token after receiving a 401.")}throw new Error("Authentication failed after maximum token retries.")}i(on,"supafetch");function mu(n){try{let e=n.split(".")[1],t=Buffer.from(e,"base64").toString("utf8");return JSON.parse(t)}catch{return null}}i(mu,"decodeJWT");function gu(n,e,t){if(n.IP&&t&&n.IP[t])return{blocked:!0,id:n.IP[t],source:`IP/${t}`};if(n.Header)for(let[r,o]of Object.entries(n.Header)){let s=e.headers.get(r);if(s){if(o.RAW&&o.RAW[s])return{blocked:!0,id:o.RAW[s],source:`Header/${r}/RAW/${s}`};if(o.JWT){let a=s;if(r.toLowerCase()==="authorization"){let c=s.split(" ");c.length===2&&c[0].toLowerCase()==="bearer"&&(a=c[1])}let u=mu(a);if(u){for(let[c,l]of Object.entries(o.JWT))if(u[c]&&l[u[c]])return{blocked:!0,id:l[u[c]],source:`Header/${r}/JWT/${c}/${u[c]}`}}}if(r.toLowerCase()==="cookie"&&o.COOKIE){let a=s.split(";").reduce((u,c)=>{let[l,d]=c.trim().split("=");return u[l]=d,u},{});for(let[u,c]of Object.entries(o.COOKIE))if(a[u]&&c[a[u]])return{blocked:!0,id:c[a[u]],source:`Header/Cookie/${u}/${a[u]}`}}}}if(n.Query){let r=new URL(e.url);for(let[o,s]of Object.entries(n.Query)){let a=r.searchParams.get(o);if(a){if(s.RAW&&s.RAW[a])return{blocked:!0,id:s.RAW[a],source:`Query/${o}/RAW/${a}`};if(s.JWT){let u=mu(a);if(u){for(let[c,l]of Object.entries(s.JWT))if(u[c]&&l[u[c]])return{blocked:!0,id:l[u[c]],source:`Query/${o}/JWT/${c}/${u[c]}`}}}}}}return{blocked:!1}}i(gu,"checkRequest");var hp="unused",sn={index:1,type:15,version:"3.2.3"},yu="REQUEST_CLONE_fc64713a-d8e9-44bf-b7a2-2edffd0db542";function yp(n){let e=te.get(n,yu);if(!e)throw new Error("AkamaiApiSecurityPlugin: Fatal error - no request clone on ContextData");return e}i(yp,"getRequestClone");function bp(n,e){te.set(n,yu,e)}i(bp,"setRequestClone");var fu,hu="plugin.akamai-api-security-plugin",Ci=class extends ye{static{i(this,"AkamaiApiSecurityPlugin")}constructor(e){super(),this.#n=e,g(hu)}async initialize(e){e.addRequestHook(async(t,r)=>{fu=r;let o=t.clone();if(bp(r,o),this.#n.enableProtection===!0)try{let s=await this.#t.get(hp);this.#n.debug&&r.log.debug("AkamaiApiSecurityPlugin: Loaded ProtectionResponse",s);let a=gu(s,t);if(a.blocked===!0)return r.log.debug(`AkamaiApiSecurityPlugin: Request Blocked by rule '${a.source}':'${a.id}'`),E.forbidden(t,r,{detail:"Access to this resource has been forbidden"})}catch(s){r.log.error(`AkamaiApiSecurityPlugin: Error loading ProtectionResponse '${s.message}'`)}return t}),new qe({name:hu,generateLogEntry:this.#r,batchPeriodSeconds:this.#n.batchPeriodSeconds,dispatchFunction:this.#o},e)}#e=i(async()=>{let e=await on(`https://${this.#n.hostname}/integrations-adapter/get-prevention-rules?source-index=${sn.index}&source-key=${this.#n.key}&source-type=${sn.type}`);if(e.status!==200)throw new Error(`Unexpected response from protection endpoint ${e.status}: ${await e.text()}`);let t=await e.text();try{return JSON.parse(t)}catch{throw new Error(`Error parsing response from protection endpoint '${t}'`)}},"#protectionFetch");#t=new rn(this.#e,{ttlSeconds:60,loaderTimeoutSeconds:60});#n;#r=i(async(e,t,r,o)=>{let s=yp(r),a=e.clone(),[u,c]=await Promise.all([s.text(),a.text()]),l=new URL(t.url),d=t.headers.get("true-client-ip")??"",p=o.requestStartTime.getTime();return{ip:{v:Rp(d),src:d},tcp:{dst:wp(l)},http:{request:{ts:p,method:t.method,url:l.pathname,headers:Object.fromEntries(t.headers.entries()),body:u},response:{ts:p+o.durationMs,status:e.status,headers:Object.fromEntries(e.headers.entries()),body:c}},source:{type:sn.type,index:sn.index,version:sn.version,key:this.#n.key}}},"#generateEntry");#o=i(async e=>{if(e.length===0)return;let t=JSON.stringify(e),r=await on(`https://${this.#n.hostname}/engine`,{method:"POST",headers:{"content-type":"application/json"},body:t,retries:1});this.#n.debug&&fu.log.debug({message:`AkamaiApiSecurityPlugin: Dispatched ${e.length} entries`,status:r.status,requestBody:t,responseText:await r.text()})},"#dispatch")};function wp(n){return n.port?parseInt(n.port):n.protocol==="https:"?443:80}i(wp,"guessPort");function Rp(n){return n.includes("::")||(n.match(/:/g)||[]).length>1?"6":"4"}i(Rp,"detectIPVersion");var Pp=i(async(n,e,t,r)=>({deploymentName:r.deploymentName,timestamp:r.requestStartTime.toISOString(),requestId:t.requestId,routePath:t.route.path,url:e.url,statusCode:n.status,durationMs:r.durationMs,method:e.method,userSub:e.user?.sub,instanceId:r.instanceId,clientIP:e.headers.get("true-client-ip")??void 0,zuploUserAgent:r.systemUserAgent}),"defaultGenerateHydrolixEntry"),bu="plugin.hydrolix-request-logger",Oi=class extends ye{static{i(this,"HydrolixRequestLoggerPlugin")}constructor(e){super(),e.batchPeriodSeconds||(e.batchPeriodSeconds=1),this.#e=e,g(bu)}async initialize(e){new qe({name:bu,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=i(async e=>{if(e.length===0)return;let t={"x-hdx-table":this.#e.table,"x-hdx-transform":this.#e.transform,"content-type":"application/json"};this.#e.token&&(t.token=this.#e.token,t.authorization=`Basic ${btoa(`${this.#e.username}:${this.#e.password}`)}`),await on(`https://${this.#e.hostname}/ingest/event`,{method:"POST",headers:t,body:JSON.stringify(e),retries:1})},"#dispatch")};var Ip="plugin.request-logger",Si=class extends ye{static{i(this,"RequestLoggerPlugin")}constructor(e){super(),this.#e=e,g(Ip)}async initialize(e){new qe(this.#e,e)}#e};async function Ep(n,e={}){g("utility.zuplo-api-services");let{method:t="GET",data:r}=e,o=new URL(n,h.instance.zuploEdgeApiUrl),s=new Headers(e.headers);_e(s),s.set("Content-Type","application/json");let a={method:t,headers:s};r&&(a.body=JSON.stringify(r));let u=await H.fetch(o,a),c;try{if(!u.ok)throw c=await u.clone().json(),new Error(`Error ${u.status}: ${JSON.stringify(c)||"Request failed"}`);if(u.status===204)return;c=await u.clone().json()}catch(l){throw new Error(l.message)}return c}i(Ep,"apiServices");var Ai=["sha-1","sha-256","sha-384","sha-512"],Vn=class{static{i(this,"BaseCryptoBeta")}};var ki=class extends Vn{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(g("runtime.crypto-beta"),!Ai.includes(e.toLowerCase()))throw new k(`Algorithm ${e} is not supported. Try using ${Ai.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};export{Co as AWSLoggingPlugin,Ci as AkamaiApiSecurityPlugin,kl as AmberfloMeteringInboundPolicy,zo as AmberfloMeteringPolicy,Nl as ApiAuthKeyInboundPolicy,Bo as ApiKeyInboundPolicy,Go as AsertoAuthZInboundPolicy,Do as AuditLogDataStaxProvider,Mo as AuditLogPlugin,Hl as Auth0JwtInboundPolicy,Kc as AwsLambdaHandlerExtensions,Ko as AxiomaticsAuthZInboundPolicy,vi as AzureBlobPlugin,nn as BackgroundDispatcher,rn as BackgroundLoader,Zl as BasicAuthInboundPolicy,Ka as BasicRateLimitInboundPolicy,Y as BatchDispatch,Xo as BrownoutInboundPolicy,Ql as CachingInboundPolicy,Yl as ChangeMethodInboundPolicy,Xl as ClearHeadersInboundPolicy,ed as ClearHeadersOutboundPolicy,td as ClerkJwtInboundPolicy,nd as CognitoJwtInboundPolicy,ii as ComplexRateLimitInboundPolicy,dd as CompositeInboundPolicy,pd as CompositeOutboundPolicy,m as ConfigurationError,kr as ContentTypes,te as ContextData,ki as CryptoBeta,md as CurityPhantomTokenInboundPolicy,oo as DataDogLoggingPlugin,Ao as DataDogMetricsPlugin,bo as DynaTraceLoggingPlugin,_o as DynatraceMetricsPlugin,fd as FirebaseJwtInboundPolicy,hd as FormDataToJsonInboundPolicy,yd as GeoFilterInboundPolicy,Xr as GoogleCloudLoggingPlugin,uo as Handler,E as HttpProblems,yn as HttpStatusCode,Oi as HydrolixRequestLoggerPlugin,ce as InboundPolicy,bd as JWTScopeValidationInboundPolicy,Ro as LokiLoggingPlugin,yt as LookupResult,ie as MemoryZoneReadThroughCache,wd as MockApiInboundPolicy,vd as MoesifInboundPolicy,ci as MonetizationInboundPolicy,li as OktaFGAAuthZInboundPolicy,Od as OktaJwtInboundPolicy,di as OpenFGAAuthZInboundPolicy,Re as OpenIdJwtInboundPolicy,Je as OutboundPolicy,rt as ProblemResponseFormatter,Ad as PropelAuthJwtInboundPolicy,gi as QuotaInboundPolicy,Ka as RateLimitInboundPolicy,Md as ReadmeMetricsInboundPolicy,qd as RemoveHeadersInboundPolicy,Ud as RemoveHeadersOutboundPolicy,Hd as RemoveQueryParamsInboundPolicy,Zd as ReplaceStringOutboundPolicy,Si as RequestLoggerPlugin,$d as RequestSizeLimitInboundPolicy,ou as RequestValidationInboundPolicy,jd as RequireOriginInboundPolicy,Ht as ResponseSendingEvent,Zt as ResponseSentEvent,k as RuntimeError,dn as SYSTEM_LOGGER,Fd as SchemaBasedRequestValidation,$e as SemanticAttributes,Ei as ServiceProviderImpl,zd as SetBodyInboundPolicy,Bd as SetHeadersInboundPolicy,Gd as SetHeadersOutboundPolicy,Vd as SetQueryParamsInboundPolicy,Wd as SetStatusOutboundPolicy,Kd as SleepInboundPolicy,Ia as StripeMonetizationPlugin,Yt as StripeWebhookVerificationInboundPolicy,Eo as SumoLogicLoggingPlugin,Qd as SupabaseJwtInboundPolicy,Ue as SystemRouteName,qt as TelemetryPlugin,Yd as UpstreamAzureAdServiceAuthInboundPolicy,ep as UpstreamFirebaseAdminAuthInboundPolicy,rp as UpstreamFirebaseUserAuthInboundPolicy,wi as UpstreamGcpFederatedAuthInboundPolicy,op as UpstreamGcpJwtInboundPolicy,ip as UpstreamGcpServiceAuthInboundPolicy,To as VMWareLogInsightLoggingPlugin,sp as ValidateJsonSchemaInbound,Ii as XmlToJsonOutboundPolicy,Nt as ZoneCache,re as ZuploRequest,tn as ZuploServices,Ep as apiServices,Qc as awsLambdaHandler,Pp as defaultGenerateHydrolixEntry,Pe as environment,Kn as getIdForParameterSchema,Iu as getIdForRefSchema,Qn as getIdForRequestBodySchema,Pu as getRawOperationDataIdentifierName,Nr as httpStatuses,il as openApiSpecHandler,al as redirectHandler,Eu as sanitizedIdentifierName,Lr as serialize,Ed as setMoesifContext,g as trackFeature,ll as urlForwardHandler,pl as urlRewriteHandler,ml as webSocketHandler,gl as webSocketPipelineHandler,ul as zuploServiceProxy};
86
+ `)}i(pp,"generateCsvContent");async function mp(n,e,t){let{sasUrl:r}=e,o=r.split("?"),s=`${o[0]}/${t}?${o[1]}`;try{let a=await H.fetch(s,{method:"PUT",headers:{"x-ms-blob-type":"BlockBlob","Content-Type":"text/csv"},body:n});a.ok||(Ti({message:a.statusText,status:a.status,details:await a.text()}),Ti({message:a.statusText,status:a.status,details:await a.text()}))}catch(a){Ti(a)}}i(mp,"uploadToAzureBlobStorage");function Ti(n){if(!pu){let t=Ke(),r=ne({level:"error",messages:["AzureBlobCsvPlugin: No context available to log user errors"]});t.waitUntil(r);return}let e;n instanceof Error?e={message:n.message,status:-1,details:n.stack??""}:e=n,pu.log.error("AzureBlobCsvPlugin: Error uploading to Azure Blob Storage",e)}i(Ti,"logError");function Gn(n,e,t){return new Promise((r,o)=>{let s=setTimeout(()=>{o(new Error(t||`Operation timed out after ${e} second(s)`))},e*1e3);n.then(a=>{clearTimeout(s),r(a)}).catch(a=>{clearTimeout(s),o(a)})})}i(Gn,"withTimeout");async function gp(n,e,t,r){let o;for(let s=0;s<t;s++)try{let a=fetch(n,e),u=r?await Gn(a,r,"Fetch timed out"):await a;if(u.ok)return u;o=new Error(`Fetch returned status ${u.status}`)}catch(a){o=a}throw o||new Error("Fetch failed without a response.")}i(gp,"fetchWithRetry");async function fp(n,e,t,r,o){let s;for(let a=0;a<r;a++)try{let u=new Headers(e.headers||{});u.set("Authorization",`Bearer ${t}`);let c={...e,headers:u},l=fetch(n,c),d=o?await Gn(l,o,"Fetch timed out"):await l;if(d.status===401||d.ok)return d;s=new Error(`Fetch returned status ${d.status}`)}catch(u){s=u}throw s||new Error("Fetch with token failed without a response.")}i(fp,"fetchWithToken");async function on(n,e={}){let{retries:t=3,timeoutSeconds:r,auth:o,...s}=e;if(!o)return await gp(n,s,t,r);let a=o.retries??3,u=o.timeoutSeconds,c;for(let l=0;l<a;l++)try{let d=o.callback();if(c=u?await Gn(d,u,"Auth token acquisition timed out"):await d,c)break}catch(d){if(l===a-1)throw d}if(!c)throw new Error("Failed to acquire token after maximum retries.");for(let l=0;l<a;l++){let d=await fp(n,s,c,t,r);if(d.status!==401)return d;for(let p=0;p<a;p++)try{let f=o.callback();if(c=u?await Gn(f,u,"Auth token acquisition timed out"):await f,c)break}catch(f){if(p===a-1)throw f}if(!c)throw new Error("Failed to refresh token after receiving a 401.")}throw new Error("Authentication failed after maximum token retries.")}i(on,"supafetch");function mu(n){try{let e=n.split(".")[1],t=Buffer.from(e,"base64").toString("utf8");return JSON.parse(t)}catch{return null}}i(mu,"decodeJWT");function gu(n,e,t){if(n.IP&&t&&n.IP[t])return{blocked:!0,id:n.IP[t],source:`IP/${t}`};if(n.Header)for(let[r,o]of Object.entries(n.Header)){let s=e.headers.get(r);if(s){if(o.RAW&&o.RAW[s])return{blocked:!0,id:o.RAW[s],source:`Header/${r}/RAW/${s}`};if(o.JWT){let a=s;if(r.toLowerCase()==="authorization"){let c=s.split(" ");c.length===2&&c[0].toLowerCase()==="bearer"&&(a=c[1])}let u=mu(a);if(u){for(let[c,l]of Object.entries(o.JWT))if(u[c]&&l[u[c]])return{blocked:!0,id:l[u[c]],source:`Header/${r}/JWT/${c}/${u[c]}`}}}if(r.toLowerCase()==="cookie"&&o.COOKIE){let a=s.split(";").reduce((u,c)=>{let[l,d]=c.trim().split("=");return u[l]=d,u},{});for(let[u,c]of Object.entries(o.COOKIE))if(a[u]&&c[a[u]])return{blocked:!0,id:c[a[u]],source:`Header/Cookie/${u}/${a[u]}`}}}}if(n.Query){let r=new URL(e.url);for(let[o,s]of Object.entries(n.Query)){let a=r.searchParams.get(o);if(a){if(s.RAW&&s.RAW[a])return{blocked:!0,id:s.RAW[a],source:`Query/${o}/RAW/${a}`};if(s.JWT){let u=mu(a);if(u){for(let[c,l]of Object.entries(s.JWT))if(u[c]&&l[u[c]])return{blocked:!0,id:l[u[c]],source:`Query/${o}/JWT/${c}/${u[c]}`}}}}}}return{blocked:!1}}i(gu,"checkRequest");var hp="unused",sn={index:1,type:15,version:"3.2.3"},yu="REQUEST_CLONE_fc64713a-d8e9-44bf-b7a2-2edffd0db542";function yp(n){let e=te.get(n,yu);if(!e)throw new Error("AkamaiApiSecurityPlugin: Fatal error - no request clone on ContextData");return e}i(yp,"getRequestClone");function bp(n,e){te.set(n,yu,e)}i(bp,"setRequestClone");var fu,hu="plugin.akamai-api-security-plugin",Ci=class extends ye{static{i(this,"AkamaiApiSecurityPlugin")}constructor(e){super(),this.#n=e,g(hu)}async initialize(e){e.addRequestHook(async(t,r)=>{fu=r;let o=t.clone();if(bp(r,o),this.#n.enableProtection===!0)try{let s=await this.#t.get(hp);this.#n.debug&&r.log.debug("AkamaiApiSecurityPlugin: Loaded ProtectionResponse",s);let a=gu(s,t);if(a.blocked===!0)return r.log.debug(`AkamaiApiSecurityPlugin: Request Blocked by rule '${a.source}':'${a.id}'`),E.forbidden(t,r,{detail:"Access to this resource has been forbidden"})}catch(s){r.log.error(`AkamaiApiSecurityPlugin: Error loading ProtectionResponse '${s.message}'`)}return t}),new qe({name:hu,generateLogEntry:this.#r,batchPeriodSeconds:this.#n.batchPeriodSeconds,dispatchFunction:this.#o},e)}#e=i(async()=>{let e=await on(`https://${this.#n.hostname}/integrations-adapter/get-prevention-rules?source-index=${sn.index}&source-key=${this.#n.key}&source-type=${sn.type}`);if(e.status!==200)throw new Error(`Unexpected response from protection endpoint ${e.status}: ${await e.text()}`);let t=await e.text();try{return JSON.parse(t)}catch{throw new Error(`Error parsing response from protection endpoint '${t}'`)}},"#protectionFetch");#t=new rn(this.#e,{ttlSeconds:60,loaderTimeoutSeconds:60});#n;#r=i(async(e,t,r,o)=>{let s=yp(r),a=e.clone(),[u,c]=await Promise.all([s.text(),a.text()]),l=new URL(t.url),d=t.headers.get("true-client-ip")??"",p=o.requestStartTime.getTime();return{ip:{v:Rp(d),src:d},tcp:{dst:wp(l)},http:{request:{ts:p,method:t.method,url:l.pathname,headers:Object.fromEntries(t.headers.entries()),body:u},response:{ts:p+o.durationMs,status:e.status,headers:Object.fromEntries(e.headers.entries()),body:c}},source:{type:sn.type,index:sn.index,version:sn.version,key:this.#n.key}}},"#generateEntry");#o=i(async e=>{if(e.length===0)return;let t=JSON.stringify(e),r=await on(`https://${this.#n.hostname}/engine`,{method:"POST",headers:{"content-type":"application/json"},body:t,retries:1});this.#n.debug&&fu.log.debug({message:`AkamaiApiSecurityPlugin: Dispatched ${e.length} entries`,status:r.status,requestBody:t,responseText:await r.text()})},"#dispatch")};function wp(n){return n.port?parseInt(n.port):n.protocol==="https:"?443:80}i(wp,"guessPort");function Rp(n){return n.includes("::")||(n.match(/:/g)||[]).length>1?"6":"4"}i(Rp,"detectIPVersion");var Pp=i(async(n,e,t,r)=>({deploymentName:r.deploymentName,timestamp:r.requestStartTime.toISOString(),requestId:t.requestId,routePath:t.route.path,url:e.url,colo:t.incomingRequestProperties.colo,city:t.incomingRequestProperties.city,country:t.incomingRequestProperties.country,continent:t.incomingRequestProperties.continent,latitude:t.incomingRequestProperties.latitude,longitude:t.incomingRequestProperties.longitude,postalCode:t.incomingRequestProperties.postalCode,metroCode:t.incomingRequestProperties.metroCode,region:t.incomingRequestProperties.region,regionCode:t.incomingRequestProperties.regionCode,timezone:t.incomingRequestProperties.timezone,asn:t.incomingRequestProperties.asn?.toString(),asOrganization:t.incomingRequestProperties.asOrganization,statusCode:n.status,durationMs:r.durationMs,method:e.method,userSub:e.user?.sub,instanceId:r.instanceId,clientIP:e.headers.get("true-client-ip")??void 0,zuploUserAgent:r.systemUserAgent}),"defaultGenerateHydrolixEntry"),bu="plugin.hydrolix-request-logger",Oi=class extends ye{static{i(this,"HydrolixRequestLoggerPlugin")}constructor(e){super(),e.batchPeriodSeconds||(e.batchPeriodSeconds=1),this.#e=e,g(bu)}async initialize(e){new qe({name:bu,generateLogEntry:this.#e.generateLogEntry,batchPeriodSeconds:this.#e.batchPeriodSeconds,dispatchFunction:this.#t},e)}#e;#t=i(async e=>{if(e.length===0)return;let t={"x-hdx-table":this.#e.table,"x-hdx-transform":this.#e.transform,"content-type":"application/json"};this.#e.token&&(t["x-hdx-token"]=this.#e.token,t.authorization=`Basic ${btoa(`${this.#e.username}:${this.#e.password}`)}`),await on(`https://${this.#e.hostname}/ingest/event`,{method:"POST",headers:t,body:JSON.stringify(e),retries:1})},"#dispatch")};var Ip="plugin.request-logger",Si=class extends ye{static{i(this,"RequestLoggerPlugin")}constructor(e){super(),this.#e=e,g(Ip)}async initialize(e){new qe(this.#e,e)}#e};async function Ep(n,e={}){g("utility.zuplo-api-services");let{method:t="GET",data:r}=e,o=new URL(n,h.instance.zuploEdgeApiUrl),s=new Headers(e.headers);_e(s),s.set("Content-Type","application/json");let a={method:t,headers:s};r&&(a.body=JSON.stringify(r));let u=await H.fetch(o,a),c;try{if(!u.ok)throw c=await u.clone().json(),new Error(`Error ${u.status}: ${JSON.stringify(c)||"Request failed"}`);if(u.status===204)return;c=await u.clone().json()}catch(l){throw new Error(l.message)}return c}i(Ep,"apiServices");var Ai=["sha-1","sha-256","sha-384","sha-512"],Vn=class{static{i(this,"BaseCryptoBeta")}};var ki=class extends Vn{static{i(this,"WorkerCryptoBeta")}async digest(e,t){if(g("runtime.crypto-beta"),!Ai.includes(e.toLowerCase()))throw new k(`Algorithm ${e} is not supported. Try using ${Ai.join(", ")}`);let r=new TextEncoder().encode(t),o=await crypto.subtle.digest(e,r);return Array.from(new Uint8Array(o)).map(u=>u.toString(16).padStart(2,"0")).join("")}};export{Co as AWSLoggingPlugin,Ci as AkamaiApiSecurityPlugin,kl as AmberfloMeteringInboundPolicy,zo as AmberfloMeteringPolicy,Nl as ApiAuthKeyInboundPolicy,Bo as ApiKeyInboundPolicy,Go as AsertoAuthZInboundPolicy,Do as AuditLogDataStaxProvider,Mo as AuditLogPlugin,Hl as Auth0JwtInboundPolicy,Kc as AwsLambdaHandlerExtensions,Ko as AxiomaticsAuthZInboundPolicy,vi as AzureBlobPlugin,nn as BackgroundDispatcher,rn as BackgroundLoader,Zl as BasicAuthInboundPolicy,Ka as BasicRateLimitInboundPolicy,Y as BatchDispatch,Xo as BrownoutInboundPolicy,Ql as CachingInboundPolicy,Yl as ChangeMethodInboundPolicy,Xl as ClearHeadersInboundPolicy,ed as ClearHeadersOutboundPolicy,td as ClerkJwtInboundPolicy,nd as CognitoJwtInboundPolicy,ii as ComplexRateLimitInboundPolicy,dd as CompositeInboundPolicy,pd as CompositeOutboundPolicy,m as ConfigurationError,kr as ContentTypes,te as ContextData,ki as CryptoBeta,md as CurityPhantomTokenInboundPolicy,oo as DataDogLoggingPlugin,Ao as DataDogMetricsPlugin,bo as DynaTraceLoggingPlugin,_o as DynatraceMetricsPlugin,fd as FirebaseJwtInboundPolicy,hd as FormDataToJsonInboundPolicy,yd as GeoFilterInboundPolicy,Xr as GoogleCloudLoggingPlugin,uo as Handler,E as HttpProblems,yn as HttpStatusCode,Oi as HydrolixRequestLoggerPlugin,ce as InboundPolicy,bd as JWTScopeValidationInboundPolicy,Ro as LokiLoggingPlugin,yt as LookupResult,ie as MemoryZoneReadThroughCache,wd as MockApiInboundPolicy,vd as MoesifInboundPolicy,ci as MonetizationInboundPolicy,li as OktaFGAAuthZInboundPolicy,Od as OktaJwtInboundPolicy,di as OpenFGAAuthZInboundPolicy,Re as OpenIdJwtInboundPolicy,Je as OutboundPolicy,rt as ProblemResponseFormatter,Ad as PropelAuthJwtInboundPolicy,gi as QuotaInboundPolicy,Ka as RateLimitInboundPolicy,Md as ReadmeMetricsInboundPolicy,qd as RemoveHeadersInboundPolicy,Ud as RemoveHeadersOutboundPolicy,Hd as RemoveQueryParamsInboundPolicy,Zd as ReplaceStringOutboundPolicy,Si as RequestLoggerPlugin,$d as RequestSizeLimitInboundPolicy,ou as RequestValidationInboundPolicy,jd as RequireOriginInboundPolicy,Ht as ResponseSendingEvent,Zt as ResponseSentEvent,k as RuntimeError,dn as SYSTEM_LOGGER,Fd as SchemaBasedRequestValidation,$e as SemanticAttributes,Ei as ServiceProviderImpl,zd as SetBodyInboundPolicy,Bd as SetHeadersInboundPolicy,Gd as SetHeadersOutboundPolicy,Vd as SetQueryParamsInboundPolicy,Wd as SetStatusOutboundPolicy,Kd as SleepInboundPolicy,Ia as StripeMonetizationPlugin,Yt as StripeWebhookVerificationInboundPolicy,Eo as SumoLogicLoggingPlugin,Qd as SupabaseJwtInboundPolicy,Ue as SystemRouteName,qt as TelemetryPlugin,Yd as UpstreamAzureAdServiceAuthInboundPolicy,ep as UpstreamFirebaseAdminAuthInboundPolicy,rp as UpstreamFirebaseUserAuthInboundPolicy,wi as UpstreamGcpFederatedAuthInboundPolicy,op as UpstreamGcpJwtInboundPolicy,ip as UpstreamGcpServiceAuthInboundPolicy,To as VMWareLogInsightLoggingPlugin,sp as ValidateJsonSchemaInbound,Ii as XmlToJsonOutboundPolicy,Nt as ZoneCache,re as ZuploRequest,tn as ZuploServices,Ep as apiServices,Qc as awsLambdaHandler,Pp as defaultGenerateHydrolixEntry,Pe as environment,Kn as getIdForParameterSchema,Iu as getIdForRefSchema,Qn as getIdForRequestBodySchema,Pu as getRawOperationDataIdentifierName,Nr as httpStatuses,il as openApiSpecHandler,al as redirectHandler,Eu as sanitizedIdentifierName,Lr as serialize,Ed as setMoesifContext,g as trackFeature,ll as urlForwardHandler,pl as urlRewriteHandler,ml as webSocketHandler,gl as webSocketPipelineHandler,ul as zuploServiceProxy};
87
87
  /*! For license information please see index.js.LEGAL.txt */
@@ -51,7 +51,7 @@ export declare interface AkamaiApiSecurityPluginOptions {
51
51
  key: string;
52
52
  batchPeriodSeconds?: number;
53
53
  enableProtection?: boolean;
54
- debug: boolean;
54
+ debug?: boolean;
55
55
  }
56
56
 
57
57
  /**
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@zuplo/runtime",
3
3
  "type": "module",
4
- "version": "6.38.13",
4
+ "version": "6.38.15",
5
5
  "repository": "https://github.com/zuplo/zuplo",
6
6
  "author": "Zuplo, Inc.",
7
7
  "exports": {