
/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Zuplo, Inc. All rights reserved.
 *
 *  This software and associated documentation files (the "Software") is intended to be used
 *  only by Zuplo customers solely to develop and test applications that will be deployed
 *  to Zuplo hosted services. You and others in your organization may use these files on your
 *  Development Devices solely for the above stated purpose.
 *
 *  Outside of uses stated above, no license is granted for any other purpose including
 *  without limitation the rights to use, copy, modify, merge, publish, distribute,
 *  sublicense, host, and/or sell copies of the Software.
 *
 *  The software may include third party components with separate legal notices or governed by
 *  other agreements, as described in licenses either embedded in or accompanying the Software.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, 
 *  INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR 
 *  PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE 
 *  FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 
 *  OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 *  DEALINGS IN THE SOFTWARE.
 *--------------------------------------------------------------------------------------------*/

var me=Object.defineProperty;var o=(r,e)=>me(r,"name",{value:e,configurable:!0});import{scheduler as ge}from"node:timers/promises";Object.defineProperty(globalThis,"scheduler",{value:ge,writable:!1,enumerable:!0,configurable:!1});function W(r){let e=0;for(let i of r)e+=i.length;let t=new Uint8Array(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return t}o(W,"concat");var k=new TextEncoder,Z=new TextDecoder,he=42,Ae=124,Ce=40,xe=33,Re=35,ye=36,Ee=44,be=45,we=58,Pe=37,Se=95,_e=62,Oe=126,Te=43,ve=61,U=k.encode(`\r
`),Le=k.encode("*"),ke=k.encode("$");function V(r){let e=[Le,k.encode(r.length.toString()),U];for(let t of r){let n=t instanceof Uint8Array?t:k.encode(t.toString());e.push(ke,k.encode(n.byteLength.toString()),U,n,U)}return W(e)}o(V,"createRequest");async function*Ne(r){let e=new Uint8Array;for await(let t of r){e=W([e,t]);let n;for(;(n=e.indexOf(U[0]))!==-1&&e[n+1]===U[1];)yield e.subarray(0,n),e=e.subarray(n+2)}}o(Ne,"readLines");function H(r,e,t=!1){return Array.fromAsync({length:e},()=>D(r,t))}o(H,"readNReplies");function R(r){return Z.decode(r.slice(1))}o(R,"parseLine");function He(r){let e=[];for(let t=0;t<r.length;t+=2)e.push(r.slice(t,t+2));return e}o(He,"chunk");async function D(r,e=!1){let{value:t}=await r.next();switch(t[0]){case he:case _e:{let n=Number(R(t));return n===-1?null:await H(r,n)}case Ae:{let n=Number(R(t))*2;return await H(r,n),D(r,e)}case Ce:return BigInt(R(t));case xe:{let{value:n}=await r.next();return Promise.reject(Z.decode(n))}case Re:return R(t)==="t";case ye:case ve:return R(t)==="-1"?null:D(r,e);case Ee:case we:switch(R(t)){case"inf":return 1/0;case"-inf":return-1/0;default:return Number(R(t))}case be:return Promise.reject(R(t));case Pe:{let n=Number(R(t))*2,i=await H(r,n);return Object.fromEntries(He(i))}case Se:return null;case Oe:return new Set(await H(r,Number(R(t)),e));case Te:return R(t);default:return e?t:Z.decode(t)}}o(D,"readReply");var $=class{static{o(this,"RedisClient")}#t;#r;#e=Promise.resolve();constructor(e){this.#t=e.writable.getWriter(),this.#r=Ne(e.readable)}#o(e){return this.#e=this.#e.then(e),this.#e}sendCommand(e,t=!1){return this.#o(()=>(this.#t.write(V(e)),D(this.#r,t)))}writeCommand(e){return this.#o(()=>this.#t.write(V(e)))}async*readReplies(e=!1){for(;;)yield D(this.#r,e)}pipelineCommands(e,t=!1){return this.#o(()=>{let n=W(e.map(V));return this.#t.write(n),H(this.#r,e.length,t)})}};var d=globalThis.Deno?.build.os==="windows"||globalThis.navigator?.platform?.startsWith("Win")||globalThis.process?.platform?.startsWith("win")||!1;function m(r){if(typeof r!="string")throw new TypeError(`Path must be a string, received "${JSON.stringify(r)}"`)}o(m,"assertPath");function y(r){return r===47}o(y,"isPosixPathSeparator");function u(r){return r===47||r===92}o(u,"isPathSeparator");function S(r){return r>=97&&r<=122||r>=65&&r<=90}o(S,"isWindowsDeviceRoot");function j(r){if(m(r),r.length===0)return"."}o(j,"assertArg");function N(r,e,t,n){let i="",c=0,l=-1,a=0,f;for(let s=0;s<=r.length;++s){if(s<r.length)f=r.charCodeAt(s);else{if(n(f))break;f=47}if(n(f)){if(!(l===s-1||a===1))if(l!==s-1&&a===2){if(i.length<2||c!==2||i.charCodeAt(i.length-1)!==46||i.charCodeAt(i.length-2)!==46){if(i.length>2){let p=i.lastIndexOf(t);p===-1?(i="",c=0):(i=i.slice(0,p),c=i.length-1-i.lastIndexOf(t)),l=s,a=0;continue}else if(i.length===2||i.length===1){i="",c=0,l=s,a=0;continue}}e&&(i.length>0?i+=`${t}..`:i="..",c=2)}else i.length>0?i+=t+r.slice(l+1,s):i=r.slice(l+1,s),c=s-l-1;l=s,a=0}else f===46&&a!==-1?++a:a=-1}return i}o(N,"normalizeString");function M(r){j(r);let e=y(r.charCodeAt(0)),t=y(r.charCodeAt(r.length-1));return r=N(r,!e,"/",y),r.length===0&&!e&&(r="."),r.length>0&&t&&(r+="/"),e?`/${r}`:r}o(M,"normalize");function K(...r){if(r.length===0)return".";r.forEach(t=>m(t));let e=r.filter(t=>t.length>0).join("/");return e===""?".":M(e)}o(K,"join");function z(r){j(r);let e=r.length,t=0,n,i=!1,c=r.charCodeAt(0);if(e>1)if(u(c))if(i=!0,u(r.charCodeAt(1))){let a=2,f=a;for(;a<e&&!u(r.charCodeAt(a));++a);if(a<e&&a!==f){let s=r.slice(f,a);for(f=a;a<e&&u(r.charCodeAt(a));++a);if(a<e&&a!==f){for(f=a;a<e&&!u(r.charCodeAt(a));++a);if(a===e)return`\\\\${s}\\${r.slice(f)}\\`;a!==f&&(n=`\\\\${s}\\${r.slice(f,a)}`,t=a)}}}else t=1;else S(c)&&r.charCodeAt(1)===58&&(n=r.slice(0,2),t=2,e>2&&u(r.charCodeAt(2))&&(i=!0,t=3));else if(u(c))return"\\";let l;return t<e?l=N(r.slice(t),!i,"\\",u):l="",l.length===0&&!i&&(l="."),l.length>0&&u(r.charCodeAt(e-1))&&(l+="\\"),n===void 0?i?l.length>0?`\\${l}`:"\\":l:i?l.length>0?`${n}\\${l}`:`${n}\\`:n+l}o(z,"normalize");function q(...r){if(r.forEach(c=>m(c)),r=r.filter(c=>c.length>0),r.length===0)return".";let e=!0,t=0,n=r[0];if(u(n.charCodeAt(0))){++t;let c=n.length;c>1&&u(n.charCodeAt(1))&&(++t,c>2&&(u(n.charCodeAt(2))?++t:e=!1))}let i=r.join("\\");if(e){for(;t<i.length&&u(i.charCodeAt(t));++t);t>=2&&(i=`\\${i.slice(t)}`)}return z(i)}o(q,"join");function _(...r){return d?q(...r):K(...r)}o(_,"join");function et(r){if(r.length>=255)throw new TypeError("Alphabet too long");let e=new Uint8Array(256);for(let s=0;s<e.length;s++)e[s]=255;for(let s=0;s<r.length;s++){let p=r.charAt(s),g=p.charCodeAt(0);if(e[g]!==255)throw new TypeError(p+" is ambiguous");e[g]=s}let t=r.length,n=r.charAt(0),i=Math.log(t)/Math.log(256),c=Math.log(256)/Math.log(t);function l(s){if(s instanceof Uint8Array||(ArrayBuffer.isView(s)?s=new Uint8Array(s.buffer,s.byteOffset,s.byteLength):Array.isArray(s)&&(s=Uint8Array.from(s))),!(s instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(s.length===0)return"";let p=0,g=0,h=0,E=s.length;for(;h!==E&&s[h]===0;)h++,p++;let b=(E-h)*c+1>>>0,C=new Uint8Array(b);for(;h!==E;){let P=s[h],x=0;for(let O=b-1;(P!==0||x<g)&&O!==-1;O--,x++)P+=256*C[O]>>>0,C[O]=P%t>>>0,P=P/t>>>0;if(P!==0)throw new Error("Non-zero carry");g=x,h++}let w=b-g;for(;w!==b&&C[w]===0;)w++;let F=n.repeat(p);for(;w<b;++w)F+=r.charAt(C[w]);return F}o(l,"encode");function a(s){if(typeof s!="string")throw new TypeError("Expected String");if(s.length===0)return new Uint8Array;let p=0,g=0,h=0;for(;s[p]===n;)g++,p++;let E=(s.length-p)*i+1>>>0,b=new Uint8Array(E);for(;p<s.length;){let P=s.charCodeAt(p);if(P>255)return;let x=e[P];if(x===255)return;let O=0;for(let G=E-1;(x!==0||O<h)&&G!==-1;G--,O++)x+=t*b[G]>>>0,b[G]=x%256>>>0,x=x/256>>>0;if(x!==0)throw new Error("Non-zero carry");h=O,p++}let C=E-h;for(;C!==E&&b[C]===0;)C++;let w=new Uint8Array(g+(E-C)),F=g;for(;C!==E;)w[F++]=b[C++];return w}o(a,"decodeUnsafe");function f(s){let p=a(s);if(p)return p;throw new Error("Non-base"+t+" character")}return o(f,"decode"),{encode:l,decodeUnsafe:a,decode:f}}o(et,"base");var oe=et;var tt="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",ne=oe(tt);import{pathToFileURL as ie}from"node:url";import se from"dotenv";var Y=class{static{o(this,"ZenoLogger")}prefix="[ZENO]:";logLevel;constructor(e="info"){this.logLevel=e}debug(...e){(this.shouldLog("debug")||Deno.env.get("ZENO_DEBUG"))&&console.debug(this.prefix,"[DEBUG]",...e)}info(...e){this.shouldLog("info")&&console.info(this.prefix,"[INFO]",...e)}warn(...e){this.shouldLog("warn")&&console.warn(this.prefix,"[WARN]",...e)}error(...e){this.shouldLog("error")&&console.error(this.prefix,"[ERROR]",...e)}shouldLog(e){let t=["debug","info","warn","error"],n=t.indexOf(this.logLevel);return t.indexOf(e)>=n}setLogLevel(e){this.logLevel=e}},A=new Y;async function ae(r){let e={};for(let[t,n]of Object.entries(Deno.env.toObject()))n!==void 0&&(e[t]=n);try{let t=_(r,".env.zuplo"),n=new TextDecoder("utf-8"),i=await Deno.readFile(ie(t)),c=n.decode(i),l=se.parse(c);for(let[a,f]of Object.entries(l))if(e[a]=f,a==="ZUPLO_SYSTEM_CONFIGURATIONS")try{let s=new TextDecoder().decode(ne.decode(f)),p=JSON.parse(s);for(let[g,h]of Object.entries(p))e[g]=String(h)}catch(s){A.error("Failed to parse ZUPLO_SYSTEM_CONFIGURATIONS from .env.zuplo:",s)}}catch(t){A.error("Error loading .env.zuplo:",t)}try{let t=_(r,".env.zuplo"),n=new TextDecoder("utf-8"),i=await Deno.readFile(ie(t)),c=n.decode(i),l=se.parse(c);for(let[a,f]of Object.entries(l))e[a]=f}catch(t){console.error("Error loading .env:",t)}for(let[t,n]of Object.entries(e))n===void 0&&delete e[t];return e}o(ae,"loadEnvironment");function le(r){return r?["true","1","yes","y"].includes(r.toLowerCase()):!1}o(le,"parseEnvBool");var Q=class{static{o(this,"CacheStorage")}#t;constructor(){this.#t=new Map}async open(e){let t=this.#t.get(e);return t||(t=new ee,this.#t.set(e,t)),t}async has(e){return this.#t.has(e)}async delete(e){throw new Error("caches.delete is not supported")}};async function rt(){let r=Deno.env.get("ZUPLO_CACHE_REDIS_HOSTNAME");if(r===void 0)throw new Error("ZUPLO_CACHE_REDIS_HOSTNAME is not set");let e=parseInt(Deno.env.get("ZUPLO_CACHE_REDIS_PORT")||"6379"),t=await Deno.connect({hostname:r,port:e});return new $(t)}o(rt,"getRedisClient");function ot(r){let e={};return r&&r.split(",").forEach(n=>{let[i,c]=n.trim().split("=");e[i.toLowerCase()]=c?c.trim():!0}),e}o(ot,"parseHeaderValue");function nt(r){let e={};for(let[t,n]of r.entries())e[t]=n;return e}o(nt,"objectifyHeaders");async function it(r){let e=await r.arrayBuffer(),t=new Uint8Array(e),n="";for(let i=0;i<t.length;i++)n+=String.fromCharCode(t[i]);return btoa(n)}o(it,"serializeResponseBody");function st(r){let e=atob(r),t=e.length,n=new Uint8Array(t);for(let i=0;i<t;i++)n[i]=e.charCodeAt(i);return n}o(st,"deserializeResponseBody");var ee=class{static{o(this,"Cache")}#t;#r;#e;constructor(e="default",t={}){this.#t=e;let n=Deno.env.get("ZUPLO_CACHE_REDIS_HOSTNAME")&&Deno.env.get("ZUPLO_CACHE_REDIS_PORT");this.#r=!n||!le(Deno.env.get("USE_ZENO_ZONE_CACHE")),this.#e=t.getRedisClient||rt}#o(e){return`${this.#t}:${e.url}`}async match(e,t){if(this.#r)return;let n=this.#o(e),i=await this.#e();await i.sendCommand(["HELLO",3]);let c=await i.sendCommand(["TTL",n]);if(c!==-2){if(c<2)return;{let l=await i.sendCommand(["HGETALL",n]),a=l.status,f=l.status,s=new Headers(JSON.parse(l.headers));return new Response(st(l.body),{status:a,statusText:f,headers:s})}}}async put(e,t){if(this.#r)return;let n=1*60*60,i=ot(t.headers.get("cache-control")),c=parseInt(i["s-maxage"]),l=parseInt(i["max-age"]),a=i["no-store"],f=i["no-cache"],s=c||l||0;if(s===0&&!a&&!f&&(s=n,t.headers.append("cache-control",`s-maxage=${n}`)),s>0){let p=this.#o(e),g=await this.#e();await g.sendCommand(["HELLO",3]),await g.sendCommand(["HSET",p,"maxage",s,"status",t.status,"statusText",t.statusText,"headers",JSON.stringify(nt(t.headers)),"body",await it(t)]),await g.sendCommand(["EXPIRE",p,s])}}async delete(e){if(this.#r)return;let t=this.#o(e);if(await(await this.#e()).sendCommand(["DEL",t])!==1)throw new Error("Failed to delete cache entry")}},at=new Q;Object.defineProperty(globalThis,"caches",{value:at,writable:!1,enumerable:!0,configurable:!1});var J=class{static{o(this,"WorkerServer")}#t;#r;#e=o(()=>({waitUntil:o(e=>{e.catch(t=>{console.error("Error in waitUntil:",t)})},"waitUntil")}),"#createContext");constructor(e){this.#r=e}async start(){let{port:e,workerModule:t,env:n}=this.#r;this.#t=Deno.serve({port:e,onListen:o(()=>{A.debug(`Server running at http://localhost:${e}`)},"onListen")},async i=>{try{return await t.default.fetch(i,n,this.#e())}catch(c){return A.error("Error handling request:",c),new Response("Internal Server Error",{status:500})}}),await this.#t.finished}async stop(){await this.#t?.shutdown()}};import{pathToFileURL as lt}from"node:url";var ce=_("dist","worker.js");function ct(){if(Deno.build.standalone)return _("..",ce);let r=Deno.cwd();return _(r,ce)}o(ct,"getDefaultWorkerPath");var ft=ct();function pt(r){return typeof r=="object"&&r!==null&&"default"in r&&typeof r.default=="object"&&"fetch"in r.default&&typeof r.default.fetch=="function"}o(pt,"isWorkerModule");async function fe(r=ft){let e;if(Deno.build.standalone?(A.debug("Loading worker module from: ",r),e=await import(r)):(A.debug("Loading dev worker module from: ",r),e=await import(lt(r).href)),!pt(e))throw new Error("Invalid worker module");return e}o(fe,"importWorkerModule");function pe(){console.log("Enabling fetch host override.");let r=globalThis.fetch,e=Deno.createHttpClient({allowHost:!0,http2:!1});return globalThis.fetch=async(t,n={})=>await r(t,{...n,client:e}),e}o(pe,"setFetchHostOverride");function ue(r){if(new.target)throw new TypeError("Cannot create an instance: parse is not a constructor");return new te(r).parse()}o(ue,"parse");var te=class{static{o(this,"JsoncParser")}#t=new Set(` 	\r
`);#r=new Set([..."[]{}:,/",...this.#t]);#e;#o;#i;constructor(e){this.#e=`${e}`,this.#o=this.#e.length,this.#i=this.#l()}parse(){let e=this.#n(),t=this.#s(e),{done:n,value:i}=this.#i.next();if(!n)throw new SyntaxError(L(i));return t}#n(){let{done:e,value:t}=this.#i.next();if(e)throw new SyntaxError("Cannot parse JSONC: unexpected end of JSONC input");return t}*#l(){for(let e=0;e<this.#o;e++)if(!this.#t.has(this.#e[e])){if(this.#e[e]==="/"&&this.#e[e+1]==="*"){e+=2;let t=!1;for(;e<this.#o;e++)if(this.#e[e]==="*"&&this.#e[e+1]==="/"){t=!0;break}if(!t)throw new SyntaxError("Cannot parse JSONC: unexpected end of JSONC input");e++;continue}if(this.#e[e]==="/"&&this.#e[e+1]==="/"){for(e+=2;e<this.#o&&!(this.#e[e]===`
`||this.#e[e]==="\r");e++);continue}switch(this.#e[e]){case"{":yield{type:"BeginObject",position:e};break;case"}":yield{type:"EndObject",position:e};break;case"[":yield{type:"BeginArray",position:e};break;case"]":yield{type:"EndArray",position:e};break;case":":yield{type:"NameSeparator",position:e};break;case",":yield{type:"ValueSeparator",position:e};break;case'"':{let t=e,n=!1;for(e++;e<this.#o&&!(this.#e[e]==='"'&&!n);e++)n=this.#e[e]==="\\"&&!n;yield{type:"String",sourceText:this.#e.substring(t,e+1),position:t};break}default:{let t=e;for(;e<this.#o&&!this.#r.has(this.#e[e]);e++);e--,yield{type:"NullOrTrueOrFalseOrNumber",sourceText:this.#e.substring(t,e+1),position:t}}}}}#s(e){switch(e.type){case"BeginObject":return this.#c();case"BeginArray":return this.#f();case"NullOrTrueOrFalseOrNumber":return this.#p(e);case"String":return this.#a(e);default:throw new SyntaxError(L(e))}}#c(){let e={};for(;;){let t=this.#n();if(t.type==="EndObject")return e;if(t.type!=="String")throw new SyntaxError(L(t));let n=this.#a(t),i=this.#n();if(i.type!=="NameSeparator")throw new SyntaxError(L(i));let c=this.#n();Object.defineProperty(e,n,{value:this.#s(c),writable:!0,enumerable:!0,configurable:!0});let l=this.#n();if(l.type==="EndObject")return e;if(l.type!=="ValueSeparator")throw new SyntaxError(L(l))}}#f(){let e=[];for(;;){let t=this.#n();if(t.type==="EndArray")return e;e.push(this.#s(t));let n=this.#n();if(n.type==="EndArray")return e;if(n.type!=="ValueSeparator")throw new SyntaxError(L(n))}}#a(e){let t;try{t=JSON.parse(e.sourceText)}catch{throw new SyntaxError(L(e))}if(typeof t!="string")throw new TypeError(`Parsed value is not a string: ${t}`);return t}#p(e){if(e.sourceText==="null")return null;if(e.sourceText==="true")return!0;if(e.sourceText==="false")return!1;let t;try{t=JSON.parse(e.sourceText)}catch{throw new SyntaxError(L(e))}if(typeof t!="number")throw new TypeError(`Parsed value is not a number: ${t}`);return t}};function L({type:r,sourceText:e,position:t}){let n="";switch(r){case"BeginObject":n="{";break;case"EndObject":n="}";break;case"BeginArray":n="[";break;case"EndArray":n="]";break;case"NameSeparator":n=":";break;case"ValueSeparator":n=",";break;case"NullOrTrueOrFalseOrNumber":case"String":n=30<e.length?`${e.slice(0,30)}...`:e;break}return`Cannot parse JSONC: unexpected token "${n}" in JSONC at position ${t}`}o(L,"buildErrorMessage");var ut="zuplo.jsonc";function de(r){let e=_(r,ut),t=Deno.readTextFileSync(e),n=ue(t);if(n!==null&&typeof n=="object"&&"managedDedicatedFlags"in n)return n.managedDedicatedFlags}o(de,"getManagedDedicatedSettings");async function dt(){let r;A.debug("Starting Zeno server...");try{let e=await fe(),t=await ae(Deno.cwd());de(Deno.cwd())?.allowFetchHostHeaderOverride&&(r=pe()),await new J({port:9e3,workerModule:e,env:t}).start()}catch(e){A.error("Failed to start server:",e)}finally{r&&r.close()}}o(dt,"main");import.meta.main&&await dt();export{dt as main};
