-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.min.js
3 lines (3 loc) · 44.2 KB
/
api.min.js
1
2
3
const random=()=>crypto.getRandomValues(new BigUint64Array([0n]))[0].toString(36),crypto=require("crypto"),fs=require("fs"),https=require("https"),http=require("http"),path=require("path"),mime=require("mime"),os=require("os"),exec=require("child_process")["exec"],stdin=process["stdin"],EventEmitter=require("events")["EventEmitter"],WS=require("ws"),open=require("open"),babel=require("@babel/core"),babelParser=require("@babel/parser"),babelGenerator=require("@babel/generator"),traverse=require("@babel/traverse").default,printer=require("fancy-printer"),esbuild=require("esbuild"),minify={js:(...e)=>require("uglify-js").minify(...e).code,css:(...e)=>require("csso").minify(...e).css,html:(...e)=>require("html-minifier-terser").minify(...e)},xss=require("xss"),url=require("url"),exit=(...e)=>{printer.dev.error(...e),process.exit(1)},isTerminal=(process.on("exit",()=>{if(global.Hizzy){var e=Hizzy.getAddons&&Hizzy.getAddons();for(const t in e)e[t].module.disable("termination")}}),process.on("SIGINT",()=>{process.exit(0)}),process.on("uncaughtException",e=>{printer.dev.error(e),process.exit(1)}),require.main.filename===path.join(__dirname,"hizzy.js")||require.main.filename===path.join(__dirname,"hizzy.min.js"));let hizzy={};const hizzyPath=path.join(__dirname,"hizzy.js"),hizzyMinPath=path.join(__dirname,"hizzy.min.js"),{args:argv,config}=hizzy=isTerminal?require(fs.existsSync(hizzyPath)?hizzyPath:hizzyMinPath):hizzy,staticJSON=JSON.stringify(config?.static),runtimeId=random(),pack=e=>JSON.stringify(e),EVERYONE=e=>{if(!e.__FUNCTION__)throw new Error("EVERYONE function only allows client-sided functions!");const t=[],i=TO_CLIENTS(e)(t);return async(...e)=>(t.length=0,t.push(...Hizzy.clientUUIDs()),i(...e))},TO_CLIENTS=n=>{if(n.__FUNCTION__)return r=>async(...e)=>{var t={};for(const i of r)t[i]=(await makeClientFunction(n.__FUNCTION__FILE__,n.__FUNCTION__,"string"==typeof i?i:i.uuid,n.__FROM__))(...e);return t};throw new Error("TO_CLIENTS function only allows client-sided functions!")},makeClientFunction=(Object.defineProperty(Function.prototype,"everyone",{get:function(){return EVERYONE(this)}}),Object.defineProperty(Function.prototype,"toClients",{get:function(){return TO_CLIENTS(this)}}),(e,i,r=null,n=null)=>{e=path.join(e);const s=JSON.stringify(e);var t=async(...e)=>{if(null===r)throw new Error("This client-sided function wasn't assigned to any clients! Although you can still use the function with the '.everyone' property of this function!");var t=Hizzy.getHash(r);return Hizzy.sendEvalTo(r,n?`args=${JSON.stringify(e)};__hizzy_run${t}__2["${n}"]("${i}(...args)")`:`args=${JSON.stringify(e)};__hizzy_run${t}__[${s}].normal.${i}(...args)`)};return t.__FUNCTION__=i,t.__FUNCTION__FILE__=e,t.__FUNCTION__FILE_J__=s,t.__FROM__=n,t}),makeBeginCode=(t,e,i,r=null)=>e.map(e=>`const ${e} = Hizzy.makeClientFunction(${i}, ${JSON.stringify(e)}, ${JSON.stringify(t)}, "${r}");`).join(""),{CLIENT2SERVER,SERVER2CLIENT}={CLIENT2SERVER:{HANDSHAKE_RESPONSE:"0",CLIENT_FUNCTION_RESPONSE:"1",SERVER_FUNCTION_REQUEST:"2",KEEPALIVE:"3",0:"HANDSHAKE_RESPONSE",1:"SERVER_FUNCTION_REQUEST",2:"CLIENT_FUNCTION_RESPONSE",3:"KEEPALIVE"},SERVER2CLIENT:{FILE_REFRESH:"0",HANDSHAKE_REQUESTED:"1",CLIENT_FUNCTION_REQUEST:"2",SERVER_FUNCTION_RESPONSE:"3",SURE_HANDSHAKE:"4",PAGE_PAYLOAD:"5",0:"FILE_REFRESH",1:"HANDSHAKE_REQUESTED",2:"CLIENT_FUNCTION_REQUEST",3:"SERVER_FUNCTION_RESPONSE",4:"SURE_HANDSHAKE",5:"PAGE_PAYLOAD"}},fx=(e,t)=>{e=(e=e.toString()).split(".");let i=e[1]||"";return i.length>t&&(i=i.substring(0,t)),e[0]+(i?"."+i:"")},timeForm=e=>864e5<=e?fx(e/24/60/60/1e3,3)+"d":36e5<=e?fx(e/60/60/1e3,3)+"h":6e4<=e?fx(e/60/1e3,3)+"m":1e3<=e?fx(e/1e3,3)+"s":e+"ms",ck="__"+__PRODUCT__+"__",jsOpt={mangle:{toplevel:!0},module:!0},HIZZY_EXPERIMENTAL=process.argv.includes("--injections");let experimentalId=Date.now().toString(36),jsxInjection,htmlInjection,preactCode,preactHooksCode;const generateInjections=async()=>{try{var e=Date.now(),t=(jsxInjection=minify.js(fs.readFileSync(path.join(__dirname,"injections/jsx.js"),"utf8"),jsOpt),fs.writeFileSync(path.join(__dirname,"injections/jsx.min.js"),jsxInjection),htmlInjection=minify.js(fs.readFileSync(path.join(__dirname,"injections/html.js"),"utf8").replace("$CKL",ck.length+1+"").replaceAll("$CK",ck),jsOpt),fs.writeFileSync(path.join(__dirname,"injections/html.min.js"),htmlInjection),preactCode=(await(await fetch("https://esm.sh/stable/preact/es2022/preact.mjs")).text()).replace("sourceMappingURL",""),fs.writeFileSync(path.join(__dirname,"injections/preact.min.js"),preactCode),preactHooksCode=(await(await fetch("https://esm.sh/stable/preact/es2022/hooks.js")).text()).replace("sourceMappingURL","").replace(/"\/stable\/preact@(\d.?)+\/es2022\/preact\.mjs"/,`"./__${__PRODUCT__}__preact__"`)+`
import *as React from "./__${__PRODUCT__}__preact__"; export{React}`,fs.writeFileSync(path.join(__dirname,"injections/hooks.min.js"),preactHooksCode),fs.writeFileSync(path.join(__dirname,"injections/.last"),experimentalId),Date.now()-e);printer.dev.pass("Injections have been minified. (%c"+timeForm(t)+"&t)","color: orange")}catch(e){printer.dev.fail("Couldn't compile the injections!"),printer.dev.error(e)}},interfaces=(HIZZY_EXPERIMENTAL?generateInjections().then(e=>e):(jsxInjection=fs.readFileSync(path.join(__dirname,"injections/jsx.min.js"),"utf8"),htmlInjection=fs.readFileSync(path.join(__dirname,"injections/html.min.js"),"utf8"),preactCode=fs.readFileSync(path.join(__dirname,"injections/preact.min.js"),"utf8"),preactHooksCode=fs.readFileSync(path.join(__dirname,"injections/hooks.min.js"),"utf8"),experimentalId=fs.readFileSync(path.join(__dirname,"injections/.last"),"utf8")),os.networkInterfaces()),addresses=[];for(const N in interfaces){const O=interfaces[N];for(const P of O)"IPv4"!==P.family||P.internal||addresses.push(P.address)}const ideaCmd={win32:"idea64.exe",darwin:"idea"}[os.platform()]||"idea.sh",phpStormCmd={win32:"phpstorm64.exe",darwin:"phpstorm"}[os.platform()]||"phpstorm.sh",webStormCmd={win32:"webstorm.exe",darwin:"webstorm"}[os.platform()]||"webstorm.sh",codeAtCache={},runCodeAt=async(e,t)=>{var i=t+"\0"+e;if(codeAtCache[i])return codeAtCache[i];t+=random()+".mjs",fs.writeFileSync(t,e);let r;try{r={success:!0,result:await import(url.pathToFileURL(t))}}catch(e){r={success:!1,result:e}}return fs.rmSync(t),codeAtCache[i]=r},runCodeAtSpecial=async(e,t,i)=>runCodeAt(`export default async (${t.join(",")}) => {${e}}`,i);class Client{static clients={};__socket;class=Client;attributes={};routes={};constructor(e){if(Client.clients[e._uuid])return Client.clients[e._uuid];this.__socket=e,Client.clients[e._uuid]=this}get uuid(){return this.__socket._uuid}get ip(){return this.__socket._req.ip}get request(){return this.__socket._req}get actualRequest(){return this.__socket._actualReq}async eval(e){return API.API.sendEvalTo(this.uuid,e)}remove(e="forced"){this.__socket._close(e)}run(e,t,...i){return makeClientFunction(e,t,this.uuid)(...i)}}class Addon{static addons={};#name;#options;#module;#init=!1;static async create(e,t){e=new Addon(e,t);return await e.init(),e}constructor(e,t){var i=e instanceof AddonModule?e.name:e;if(Addon.addons[i])return Addon.addons[i];e instanceof AddonModule&&(this.#init=!0,this.#module=e,printer.dev.pass("Loaded addon: %c"+this.#module.name+"@"+this.#module.version,"color: blue")),this.#name=i,this.#options=t}async init(){var e=Date.now(),t=this["name"];if(!(Addon.addons[t]=this).#init){this.#init=!0;try{var i=path.join(Hizzy.directory,"node_modules",t,"package.json");if(!fs.existsSync(i)||!fs.statSync(i).isFile())throw printer.dev.fail("No package.json found for the addon %c"+t+"&t. Try installing it by using%c npm install "+t+"&t","color: orange","color: orange"),"";var r=JSON.parse(fs.readFileSync(i,"utf8"));this.#module=new(await import(url.pathToFileURL(path.join(Hizzy.directory,"node_modules",t,r.main)))).default(r,this.#options)}catch(e){return printer.dev.fail("Failed to require addon: %c"+this.name+"&t, disabling it...","color: orange"),printer.dev.error(e),void delete Addon.addons[t]}"function"==typeof this.#module.onLoad&&this.#module.onLoad();i=Date.now()-e;printer.dev.pass("Loaded addon: %c"+this.#module.name+"@"+this.#module.version+" &t(%c"+timeForm(i)+"&t)","color: blue","color: orange")}}get options(){return this.#options}get name(){return this.#name}get module(){return this.#module}}class AddonModule{#pkg;#options;constructor(e,t){this.#pkg=e,this.#options=t}get name(){return this.#pkg.name}get description(){return this.#pkg.description}get version(){return this.#pkg.version}get options(){return this.#options}onLoad(){}onEnable(){}onDisable(e){}onClientSideLoad="";onClientSideRendered="";onClientSideError="";disable(e){printer.dev[e?"fail":"debug"]("Disabling addon %c"+this.name+"&t"+(e?" for "+e:"")+"...","color: orange"),this.onDisable()}log(...e){printer.dev.log("["+this.constructor.name+"] ",...e)}}class API extends EventEmitter{static API=null;Addon=Addon;Client=Client;AddonModule=AddonModule;#listening=!1;#realtime=!1;#isBuilding=!1;#isScanningBuild=!1;#dir;#buildCache=null;#buildPromise=new Promise(e=>e());#builtAt=null;#buildRuntimeId=null;#scanPromise=new Promise(e=>e());#webUUIDs={};#clients={};#jsxCache={};#jsxFunctions={};#port=-1;#https=config.https;#serverAddress;#evalId=0;#evalResponses={};#isInputOn=!1;#hashes={};#initFunctions=[];#importMap={};#watchingFiles={};#isInit=!1;#uuidTimeout={};#builtJSXCache={};#builtJSXPage={};#clientPages={};#firstBuild=!0;#firstScan=!0;#addonCache=null;#globalStates=new Map;#startPacket={};#mainDoneCb={};server;socketServer;autoRefresh=!1;dev=!1;customShortcuts={};preRequests=[];preRawSend=[];buildHandlers={};scanHandlers={};functionDecorators={};preFileHandlers={};filePacketHandlers={};constructor(e){if(API.API)return API.API;super(),(API.API=this).#dir=e;e=this.app=require("express")();e.disable("x-powered-by"),this.server=(this.#https?https:http).createServer(e)}async init(){if(!this.#isInit){this.#isInit=!0,this.app.use(async(t,i,r)=>{i.setHeader("X-Powered-By","Hizzy");var e,n=this.getCookie(t.headers.cookie,ck),s=this.#clients[n];if(printer.dev.debug("request: "+t.url+", method: "+t.method+", ip: "+(t.ip.startsWith("::ffff:")?t.ip.substring(7):t.ip)),!this.dev&&(this.#isBuilding||this.#isScanningBuild))return i.send("Building, please be patient.<script>setTimeout(()=>location.reload(),1000)<\/script>");let o=t.url.split("?")[0].split("#")[0];if("/"===o[0])if(o=o.substring(1),t.__socket=s,t._uuid=n,s&&(s._req=t),s&&o===runtimeId+`/__${__PRODUCT__}__addons__`)(e=+config.cache.addons)&&0<e&&i.setHeader("Cache-Control","max-age="+e),await this.sendRawFile(".json",this.#addonCache,t,i);else{if(s&&o.includes("/")&&o.split("/")[0]===`__${__PRODUCT__}__npm__`)return(e=+config.cache.npm)&&0<e&&i.setHeader("Cache-Control","max-age="+e),(e=o.split("/")[2])?this.#importMap[e]?void await this.sendRawFile(".js",this.#importMap[e].code,t,i):this.sendRawFile(".js",`throw "Module not found: ${JSON.stringify(e)}"`,t,i):void 0;if(s&&o===experimentalId+"/__"+__PRODUCT__+"__preact__")(e=config.cache.preact||0)&&0<e&&i.setHeader("Cache-Control","max-age="+e),await this.sendRawFile(".js",preactCode,t,i);else if(s&&o===experimentalId+"/__"+__PRODUCT__+"__preact__hooks__")(e=config.cache["preact-hooks"]||0)&&0<e&&i.setHeader("Cache-Control","max-age="+e),await this.sendRawFile(".js",preactHooksCode,t,i);else if(this.#webUUIDs[n]&&!s&&o===experimentalId+"/__"+__PRODUCT__+"__injection__html__")(e=config.cache["html-injection"]||0)&&0<e&&i.setHeader("Cache-Control","max-age="+e),await this.sendRawFile(".js",`(async()=>{${htmlInjection}})()`,t,i);else if(this.#webUUIDs[n]&&!s&&o===experimentalId+"/__"+__PRODUCT__+"__injection__jsx__")(e=config.cache["jsx-injection"]||0)&&0<e&&i.setHeader("Cache-Control","max-age="+e),await this.sendRawFile(".js",`(async()=>{${jsxInjection}})()`,t,i);else{const a=e=>{if(e===this.preRequests.length)return r();this.preRequests[e](t,i,()=>a(e+1))};await a(0)}}}),this.dev&&!fs.existsSync(path.join(this.#dir,config.srcFolder))&&(printer.dev.warn("No %c/"+config.srcFolder+"&t found. Forcing to disable the developer mode.","color: orange"),this.dev=!1),this.buildHandlers.jsx=this.buildHandlers.tsx=[async(e,t,i,r,n,s)=>{t=await this.readClientJSX([...s,e].join("/"),t.toString());i(t.code),delete t.code,r.file("jsx/"+s.map(e=>e+"/").join("")+e.substring(0,e.length-4)+".json",JSON.stringify(t))}];var e=async(e,t,i,r,n)=>{i(t.length?await minify[n](t.toString()):"")},e=(this.buildHandlers.html=[e],this.buildHandlers.js=[e],this.buildHandlers.css=[e],async(t,e,i)=>{e=e.toString();var r,n="jsx/"+t.substring(0,t.length-4)+".json";try{if(!i[n])throw new Error("File not found: "+n);r=JSON.parse(await i[n].async("string")),await this.#pseudoBuildJSX(t,e,r,this.#initFunctions)}catch(e){printer.dev.warn("Couldn't scan JSX: '"+t+"', meta file is missing or corrupted. Try rebuilding."),printer.dev.error(e)}});this.scanHandlers.source={jsx:[e],tsx:[e],__default__:[(e,t)=>this.#buildCache[e]=t]};const o=({name:e,pth:t,json:i,getIdentifiers:r,tempName:n})=>{const s=config.serverClientVariables?r(t):null;i.functionIdentifiers[n]=s,i.after.push(()=>{t.insertAfter(babelParser.parse(`function ${e}(...args){return FN${runtimeId}("${n}",args`+(s&&s.length?`,${JSON.stringify(s)}.map(i=>eval(\`try{\${i}}catch(e){undefined}\`))`:"")+`);}SRH${runtimeId}("${n}",r=>eval(r));`)),t.remove()})};this.functionDecorators["@server"]=({name:e,pth:t,json:i,code:r,getIdentifiers:n})=>{var s=random();o({name:e,pth:t,json:i,code:r,getIdentifiers:n,tempName:s}),i.serverFunctions[s]={name:e,r:!1,code:r}},this.functionDecorators["@server/respond"]=({name:e,pth:t,json:i,code:r,getIdentifiers:n})=>{var s=random();o({name:e,pth:t,json:i,code:r,getIdentifiers:n,tempName:s}),i.serverFunctions[s]={name:e,r:!0,code:r}},this.functionDecorators["@server/start"]=({name:e,pth:t,json:i,code:r})=>{t.remove(),i.serverInit.push({name:e,code:r})},this.functionDecorators["@server/join"]=({name:e,pth:t,json:i,code:r})=>{t.remove(),i.joinEvent.push({name:e,code:r})},this.functionDecorators["@server/leave"]=({name:e,pth:t,json:i,code:r})=>{t.remove(),i.leaveEvent.push({name:e,code:r})},this.functionDecorators["@client"]=({name:e,pth:t,json:i})=>{t.insertAfter(babelParser.parse(`CFN${runtimeId}.normal.${e}=${e};`).program.body[0]),i.clientFunctionList.push(e)},this.functionDecorators["@client/render"]=({name:e,pth:t})=>{t.insertAfter(babelParser.parse(`CFN${runtimeId}.load.${e}=${e};`).program.body[0])},this.functionDecorators["@client/navigate"]=({name:e,pth:t})=>{t.insertAfter(babelParser.parse(`CFN${runtimeId}.navigate.${e}=${e};`).program.body[0])},this.preFileHandlers.css=(e,t,i,r)=>{i(".js"),r(`let st=document.createElement("style");st.innerHTML=${JSON.stringify(t.toString())};document.head.appendChild(st);export default st`)},this.preFileHandlers.html=(e,t,i,r)=>{i(".js"),r(`export default new DOMParser().parseFromString(${JSON.stringify(t.toString())},"text/html")`)}}}findOptimalFile(e){return fs.existsSync(e)&&fs.statSync(e).isFile()?e:null}cacheDevFile(e){return fs.readFileSync(e)}async cacheBuildFile(e){return this.#buildCache||(await this.#scanPromise,await this.scanBuild()),this.#buildCache[e]}async notFound(e,t){t.headersSent||t.send(`<pre>Not found: ${xss.filterXSS(e.url)}</pre>`)}prepLoad(e,t){e._uuid=t._uuid=crypto.randomUUID(),this.#webUUIDs[e._uuid]=e._Route,t.cookie(ck,t._uuid),0<config.connectionTimeout&&this.#realtime&&(this.#uuidTimeout[e._uuid]=setTimeout(()=>{delete this.#webUUIDs[e._uuid]},config.connectionTimeout))}random(){return random()}enableRealtime(){var e;if(!this.#realtime)return this.#realtime=!0,(e=this.socketServer=new WS.WebSocketServer({server:this.server})).on("connection",(g,e)=>{const _=this.getCookie(e.headers.cookie,ck);g._uuid=_;let y={};g._handshook=!1,g._closed=!1,g._req=e,g._actualReq=e;e=this.#clientPages[_]||[];g._clientPages=e[0],g._mainFile=e[1],g._URL_=this.#webUUIDs[_];const v=!!e[0],S=(delete this.#clientPages[_],new Client(g)),w=(g._send=e=>{argv["debug-socket"]&&printer.dev.debug("> "+e),g._closed||g.send(e)},clearTimeout(this.#uuidTimeout[_]),g._close=(e,t=!0)=>{if(clearTimeout(j),clearTimeout(n),!g._closed){if(g._handshook&&v&&g._mainFile){const i=g._clientPages[g._mainFile].json,r=i.leaveEvent;(async()=>{var e=await runCodeAtSpecial(`${i.serverImportCode};${y[g._mainFile]()};`+r.map(e=>`try{(${e.code})()}catch(e){printer.dev.error(e)}`).join(""),["currentUUID","currentClient"],path.join(this.#dir,config.srcFolder,g._mainFile));if(!e.success)return printer.dev.error(e.result);try{await e.result.default(_,S)}catch(e){printer.dev.error(e)}})()}t&&(g.close(),printer.dev.debug("socket remove: "+(g._uuid||"-1")+", "+e)),g._closed=!0,delete this.#clients[_],Client.clients[_]&&delete Client.clients[_]}});let n,t;const b=()=>{config.keepaliveTimeout<0||!g._URL_.endsWith(".jsx")&&!g._URL_.endsWith(".tsx")||(!t||t+config.minClientKeepalive<Date.now())&&(clearTimeout(n),t=Date.now(),n=setTimeout(()=>w("couldn't stay alive"),config.keepaliveTimeout))},j=0<config.connectionTimeout?setTimeout(e=>w("timeout"),config.connectionTimeout):null;if(!_||this.#clients[_]||!(_ in this.#webUUIDs))return w("invalid key");this.#clients[_]=g,delete this.#webUUIDs[_],printer.dev.debug("socket add: "+_),g._send(SERVER2CLIENT.HANDSHAKE_REQUESTED);const s=()=>g._clientPages&&Object.keys(g._clientPages).forEach(e=>{if(e&&(e.endsWith(".jsx")||e.endsWith(".tsx"))){const t=g._clientPages[e].json.clientFunctionList,i=JSON.stringify(e);y[e]=e=>makeBeginCode(_,t,i,e)}}),E=(s(),async()=>{if(g._mainFile){var e=g._clientPages[g._mainFile].json,t=e.joinEvent,e=await runCodeAtSpecial(`${e.serverImportCode};${y[g._mainFile]()};`+t.map(e=>`try{(${e.code})()}catch(e){printer.dev.error(e)}`).join(""),["currentUUID","currentClient"],path.join(this.#dir,config.srcFolder,g._mainFile));if(!e.success)return w("internal server error"),printer.dev.error(e.result);try{await e.result.default(_,S)}catch(e){return w("internal server error"),printer.dev.error(e)}}}),C=e=>{g._closed||g.send(SERVER2CLIENT.PAGE_PAYLOAD+""+e)};g._externalLoad=(e,t,i,r)=>{t&&(g._clientPages=t[0],g._mainFile=t[1],g._URL_=e,s(),E().then(e=>e),r||C(i))},b(),g.on("message",async t=>{if(g._closed)return w("bypass attempt");clearTimeout(j);try{if(t=t.toString(),!g._closed)if(argv["debug-socket"]&&printer.dev.debug("< "+t),t[0]===CLIENT2SERVER.HANDSHAKE_RESPONSE){if(g._handshook)return w("one handshake is enough");g._handshook=!0,g._send(SERVER2CLIENT.SURE_HANDSHAKE);var e=this.#startPacket[g._uuid];delete this.#startPacket[g._uuid],E(),e&&C(e)}else{if(!g._handshook)return w("haven't handshook");if(g._URL_.endsWith(".jsx")||g._URL_.endsWith(".tsx"))if(t[0]===CLIENT2SERVER.SERVER_FUNCTION_REQUEST){if(!v)return w("unauthorized");var n=t.substring(1).split(":"),s=n[0],o=n[1],a=n[2];if("function"!=typeof y[o]||"object"!=typeof g._clientPages[o])return w("invalid jsx");var l=g._clientPages[o].json,c=l.serverFunctions[a];if(!c)return w("invalid function");if(this.#hashes[_]){let i;try{i=JSON.parse(n.slice(3).join(":"))}catch(e){return w("invalid json")}if("object"!=typeof i||!Array.isArray(i)||"object"!=typeof i[0]||!Array.isArray(i[0])||"object"!=typeof i[1]||!Array.isArray(i[1])||2!==i.length)return w("invalid function args");let e,t,r={};var d=l.functionIdentifiers[a];if(config.serverClientVariables&&d&&d.length){if(d.length!==i[1].length)return w("an attempt of an exploit");d.map((e,t)=>[e,i[1][t]]).filter(e=>!global[e[0]]).forEach(e=>{e[1]&&(r[e[0]]=e[1])})}var u=""+Object.keys(r).map(e=>`if((typeof ${e})[0]=="u"){var ${e}=I${runtimeId}.${e}}`).join("");try{var h=await runCodeAtSpecial(`${l.serverImportCode};${y[o](a)};${u}return await (${c.code})(...ARGS${runtimeId})`,["currentUUID","currentClient","I"+runtimeId,"...ARGS"+runtimeId],path.join(this.#dir,config.srcFolder,g._mainFile));h.success?e=await h.result.default(_,S,r,...i[0]):t=h.result}catch(e){t=e}if(t)return printer.dev.error(t),w("internal server error");if(c.r){let t;try{t=JSON.stringify(e)}catch(e){t="undefined",printer.dev.fail("Couldn't stringify the response from the '@server/respond -> "+c.name+"' function at '/"+g._URL_+"'."),printer.dev.error(e)}g._send(SERVER2CLIENT.SERVER_FUNCTION_RESPONSE+s+":"+t)}}}else if(t[0]===CLIENT2SERVER.CLIENT_FUNCTION_RESPONSE){if(!v)return w("unauthorized");var i="1"===t[1],r=t.substring(2).split(":"),p=r[0];if(!p||!this.#evalResponses[p])return w("invalid eval");var f=r.slice(1).join(":");let e;var m={true:!0,false:!1,null:null,undefined:void 0};try{e=f in m?m[f]:i?new Error(f):JSON.parse(f)}catch(e){return w("invalid json")}this.#evalResponses[p](e),delete this.#evalResponses[p]}else t[0]===CLIENT2SERVER.KEEPALIVE&&b()}}catch(e){printer.dev.error(e),w("internal server error")}}),g.on("close",()=>w("disconnect",!1))}),e}async#builtJSX(i,r,s,o,a,l){if(!a[i=path.join(i).replaceAll("\\","/")]&&!o.headersSent)if(this.#builtJSXCache[i])a[i]=this.#builtJSXCache[i],l[i]=a[i].pk;else{let t;if(this.dev){var c=[];if(r=(t=await this.#pseudoBuildJSX(i,r,null,c)).code,delete t.code,c.length)return printer.dev.fail("A function with the decorator @server/start was found. Please use the main file instead.\n Note: @server/start decorator can only be used in production mode!"),void o.json({error:"Internal server error"})}else t=this.#jsxFunctions[i];if(t){const m=t.serverFunctions;var c=Object.keys(m),d=path.join(this.#dir,"node_modules");let e=t.importList;if(config.allowAllPackages&&fs.existsSync(d))for(const _ of e=fs.readdirSync(d))this.#getPackageImport(_);a[i]={code:r,json:t,pk:{code:r,functions:c.filter(e=>!m[e].r),respondFunctions:c.filter(e=>m[e].r),importList:e.map(e=>[e,(this.#importMap[e]||{}).version||""])}},l[i]=a[i].pk,this.dev||(this.#builtJSXCache[i]=a[i]);let n=s._Allow;const g=s._Deny;if("*"===g)n=[];else if("*"===n)if(this.dev){n=[];const y=e=>{const t=path.join(this.#dir,config.srcFolder,e).replaceAll("\\","/"),i=fs.readdirSync(t);for(const r of i){const i=path.join(t,r).replaceAll("\\","/");if(!fs.existsSync(i))return;if(fs.statSync(i).isFile()){const t=(e?e+"/":"")+r;g.includes(t)||n.push(t)}else y((e?e+"/":"")+r)}};y("")}else n=Object.keys(this.#buildCache).filter(e=>!g.includes(e));else"auto"===n&&(n=t.fileImportList.map(e=>path.join(path.dirname(i),e)));var u,h=async e=>{var t;return this.dev?(t=path.join(this.#dir,config.srcFolder,e),fs.existsSync(t)&&fs.statSync(t).isFile()?this.cacheDevFile(t):void 0):this.cacheBuildFile(e)};for(u of n){let e;var p,f=path.join(u).replaceAll("\\","/");let t=f;if(path.extname(f))u=t,e=await h(t);else for(const v of["tsx","jsx","ts","js"]){if(void 0!==(e=await h(t))){u=t;break}t=f+"."+v}g.includes(u)||a[u]||void 0===e||(e=e||"",this.watchFile(u),u.endsWith(".jsx")||u.endsWith(".tsx")?await this.#builtJSX(u,e,s,o,a,l):(e instanceof Buffer&&(p=path.extname(u).substring(1),e=["js","html","css"].includes(p)?e.toString():(p=this.filePacketHandlers[p])?await p(u,e):[...e]),a[u]=e,l[u]=e))}}else printer.dev.fail("Couldn't find the JSX file in build: "+i),o.json({error:"Internal server error"})}}async renderJSX(t,i,r,n,s=!1){if(!n.headersSent){this.prepLoad(r,n);var o=random();if(!this.#realtime)return n.json({error:"Expected 'realtime' option in the Hizzy configuration file to be true."});if(s&&r.__socket){if("string"!=typeof r.headers["hizzy-payload-id"]||r.headers["hizzy-payload-id"].includes("\0"))return;const a=await this.#getPagePacket(t,i,r,n);if(n.headersSent)return;r.__socket._externalLoad(t,this.#clientPages[r._uuid],r._RouteJSON+"\0"+r.headers["hizzy-payload-id"]+"\0"+a,"yes"===r.headers["hizzy-cache"])}if(r.__socket)return n.send("<script>location.reload()<\/script>");this.#hashes[r._uuid]=o;const a=await this.#getPagePacket(t,i,r,n);this.#startPacket[r._uuid]=r._RouteJSON+"\0\0"+a;s=`['${o}','${this.#buildRuntimeId||runtimeId}',`+`${0<config.keepaliveTimeout?config.clientKeepalive:-1},${this.dev?1:0},`+`'${experimentalId}',${staticJSON}]`;let e;this.dev?(t=this.findOptimalFile(path.join(this.#dir,config.srcFolder,config.baseHTML)))&&(e=this.cacheDevFile(t)):e=await this.cacheBuildFile(path.join(config.baseHTML).replaceAll("\\","/")),await this.sendRawFile(".html",`${e||""}<script type=module data-rm=${o}>(async()=>{const $$CONF$$=${s};eval(await (await fetch("/${experimentalId}/__${__PRODUCT__}__injection__jsx__")).text())})()</script>`,r,n)}}async#getPagePacket(e,t,i,r){let n={},s={},o;var a=i.url.split("?")[0].split("#")[0];if(this.#builtJSXPage[a])[n,o]=this.#builtJSXPage[a];else{try{await this.#builtJSX(e,t,i,r,n,s)}catch(e){return printer.dev.error(e),void r.json({error:"Internal server error"})}if(r.headersSent)return;o=JSON.stringify(s),this.#builtJSXPage[a]=[n,o]}return this.#clientPages[i._uuid]=[n,path.join(e).replaceAll("\\","/")],this.watchFile(i._Route),o}async renderHTML(e,t,i,r){this.prepLoad(i,r);var n=random(),s=(this.watchFile(i._Route),`['${n}',${0<config.keepaliveTimeout?config.clientKeepalive:-1}]`);await this.sendRawFile(".html",t+(this.#realtime?`<script type=module data-rm=${n}>(async()=>{const $$CONF$$=${s};eval(await (await fetch("/${experimentalId}/__${__PRODUCT__}__injection__html__")).text())})()</script>`:""),i,r)}watchFile(e){var t=path.join(e);this.dev&&!this.#watchingFiles[t]&&this.autoRefresh&&(this.#watchingFiles[t]=!0,fs.watchFile(path.join(this.#dir,config.srcFolder,e),{interval:1},()=>{this.#builtJSXPage={};for(const e in this.#clients)this.#clients[e]._send(SERVER2CLIENT.FILE_REFRESH)}))}async sendRawFile(e,t,i,r,n=!1){if(!r.headersSent){if(!n)for(const s of this.preRawSend)if(await s(e,t,i,r),r.headersSent)return;r.setHeader("Content-Type",mime.getType(e)),r.send(t)}}async sendFile(t,i,e,r,n=!1){var s="script"===e.headers["sec-fetch-dest"]||"script"===e.headers["hizzy-dest"];if(s&&!e.__socket)return r.json({error:"Unauthorized"});if(!n&&(t.endsWith(".jsx")||t.endsWith(".tsx")))return this.renderJSX(t,i,e,r,s);if(!n&&t.endsWith(".html")&&!s)return this.renderHTML(t,i,e,r);n=this.preFileHandlers[t.split(".").slice(-1)[0]];if(s&&n){let e=!1;if(n(t,i,e=>t=e,e=>i=e,()=>e=!0),e)return}await this.sendRawFile(t,i,e,r)}#staticRender(e,t){if(0!==Object.keys(config.static).length){var i=e.url.substring(1).split("?")[0].split("#")[0];for(const s in config.static){var r=config.static[s],r=r?path.join(r).replaceAll("\\","/")+"/":"";if(!r||i.startsWith(r)){var n,r=i.substring(r.length),r=path.join(this.#dir,s,r);if(fs.existsSync(r)&&fs.statSync(r).isFile())return t.headersSent?void 0:((n="object"==typeof config.cache.static?+config.cache.static[s]:+config.cache.static)&&0<n&&t.setHeader("Cache-Control","max-age="+n),this.sendFile(i,fs.readFileSync(r),e,t,!1))}}}return this.notFound(e,t)}#invalidFile(e,t){e.send("Couldn't find the file. "+(this.dev?"File does not exist: "+xss.filterXSS(t):"Please report this to the owner of the web site."))}#devRender(e,t,i){var r=path.join(this.#dir,config.srcFolder,e);return fs.existsSync(r)&&fs.statSync(r).isFile()?(r=this.cacheDevFile(r))?void this.sendFile(e,r,t,i).then(e=>e):this.#invalidFile(i,e):this.#staticRender(t,i)}async#buildRender(e,t,i){e=e.replaceAll("\\","/");var r=await this.cacheBuildFile(e);if(!r)return this.#invalidFile(i,e);await this.sendFile(e,r,t,i)}#formatLocalURL(e){var t=this.#serverAddress["port"];return`http${this.#https?"s":""}://${e}${80===t?"":":"+t}/`}#sendURLs(){var{address:e,family:t}=this.#serverAddress;printer.raw.log(" %c➜%c Local: %c"+this.#formatLocalURL("IPv6"===t?"localhost":e),"color: greenBright","","color: cyan"),argv.host?printer.raw.log(" %c➜%c Network: %c"+addresses.map(e=>this.#formatLocalURL(e)).join(", "),"color: greenBright","","color: cyan"):printer.raw.log(" %c➜ Network: use %c--host%c to expose","color: gray","","color: gray")}openInBrowser(){open("http://localhost:"+this.#port)}async#hasVSC(){return new Promise(t=>exec("where code",e=>t(!e)))}async#hasIdea(){return new Promise(t=>exec("where "+ideaCmd,e=>t(!e)))}async#hasPhpStorm(){return new Promise(t=>exec("where "+phpStormCmd,e=>t(!e)))}async#hasWebStorm(){return new Promise(t=>exec("where "+webStormCmd,e=>t(!e)))}async listen(){this.#listening&&await new Promise(e=>this.server.close(e)),this.#listening=!1;let t=Math.floor(+(argv.port||config.port));if(t<0&&(t=0),this.#port=t,await new Promise(e=>this.server.listen(t,()=>e(!0))),this.#listening=!0,this.#isInputOn)return;this.#isInputOn=!0;const i=this.getAddons();for(const c in i)i[c].module.onEnable();if(!this.#addonCache){const i=this.getAddons();var r=[];for(const d in i){var n=i[d];let e=[n.module.name,n.module.onClientSideLoad,n.module.onClientSideRendered,n.module.onClientSideError];e.slice(1).every(e=>!e)||(e=this.dev?e.map((e,t)=>0===t?e:(e||"")+""):e.map((e,t)=>{if(0===t)return e;e=(e||"")+"";t=require("uglify-js").minify(e,{compress:!1});return e?t.code:""}),r.push(e))}this.#addonCache=JSON.stringify(r)}this.#initFunctions.forEach(e=>e());var e=(this.#serverAddress=this.server.address())["port"];if(this.#port=e,this.dev||printer.println(""),printer.raw.log(" %cHIZZY v"+__VERSION__+"%c ready in%c "+timeForm(Date.now()-__sT__),"color: yellow","color: gray",""),delete global.__sT__,printer.println(""),printer.inline.log(" %c➜%c Mode: %c"+(this.dev?"Development":"Production"),"color: greenBright","","color: "+(this.dev?"orange":"green")),t<=0&&printer.inline.log("%c, randomized port","color: gray"),argv.debug&&printer.inline.log("%c, debugging","color: gray"),printer.inline.print("\n"),this.#sendURLs(),!stdin||!stdin.isTTY)return;printer.raw.log(` %c➜%c press %ch%c to show help
`,"color: gray","color: gray","color: whiteBright","color: gray"),stdin.setRawMode(!0),stdin.resume();const s={h:{description:"show this menu",enabled:!0,cooldown:1e3,run:()=>{printer.raw.println(""),printer.raw.log(" Shortcuts");for(const t in s){var e=s[t];e.enabled&&printer.raw.log("%c press %c"+t+"%c to "+e.description,"color: gray","","color: gray")}printer.raw.println("")}},r:{description:"restart the server",enabled:!0,run:async()=>{this.#listening&&(await this.listen(),printer.raw.log("%c ➜ Restarted the server.","color: green"))}},f:{description:"re-run the main file",enabled:this.dev,run:async()=>{await this.processDevMain(),printer.raw.log("%c ➜ Main file has been re-run.","color: green")}},b:{description:"build",enabled:!this.dev,run:async()=>{await this.build(),await this.scanBuild()}},s:{description:"re-scan the build",enabled:!this.dev,run:async()=>this.scanBuild()},u:{description:"show server url",enabled:!0,cooldown:1e3,run:()=>{printer.raw.println(""),this.#sendURLs(),printer.raw.println("")}},o:{description:"open in browser",enabled:!0,cooldown:1e3,run:()=>this.openInBrowser()},c:{description:"clear the console",enabled:!0,run:()=>printer.clear()},a:{description:"re-enable all addons",enabled:!0,run:()=>{var e=this.getAddons();for(const t in e)e[t].module.disable("shortcut");printer.raw.log("%c ✓ All addons have been disabled.","color: green");for(const i in e)e[i].module.onEnable();printer.raw.log("%c ✓ All addons have been enabled.","color: green")}},e:{enabled:!1},q:{description:"quit",enabled:!0,run:()=>{printer.raw.log("%c ✕ Stopping the process...","color: red; font-weight: bold"),process.exit()}},...this.customShortcuts};Promise.all([this.#hasVSC(),this.#hasIdea(),this.#hasPhpStorm(),this.#hasWebStorm()]).then(e=>{const i=[];e.forEach((e,t)=>e&&i.push({name:["Visual Studio Code","Intellij Idea","Php Storm","Web Storm"][t],command:["code",ideaCmd,phpStormCmd,webStormCmd][t]})),i.length&&(s.e={description:"opens an editor in here",enabled:!0,cooldown:1e3,run:async()=>{printer.raw.print(printer.substitute("%c ✓ Select an editor: ","color: gray")),stdin.off("data",l);var e=await printer.readSelectionListed(["Cancel",...i.map(e=>e.name)],{betweenText:" / ",normalColor:"yellow",selectedColor:"green",selectedBackgroundColor:"",selectedUnderline:!0});if(stdin.setRawMode(!0),stdin.resume(),stdin.on("data",l),0!==e){const t=i[e-1];printer.raw.log("%c ✓ Opening "+t.name+"...","color: yellow"),await new Promise(e=>exec(t.command+" "+JSON.stringify(this.#dir),e)),printer.raw.log("%c ✓ Opened "+t.name+"!","color: green")}}})});let o=null,a={},l;stdin.on("data",l=async e=>{if("\f"===(e=e.toString()))return printer.clear();""===e&&(printer.raw.log("%c ✕ Stopping the process...","color: red; font-weight: bold"),process.exit());const t=s[e];!t||!t.enabled||(a[e]||0)+(t.cooldown||0)>Date.now()||(await o,o=(async()=>{await t.run(),a[e]=Date.now()})())}),argv.open&&this.openInBrowser()}async#buildInternal(r,n=[0],e){var t=path.join(this.#dir,config.srcFolder);for(const l of fs.readdirSync(path.join(t,...r))){var s=path.join(t,...r,l);if(fs.existsSync(s))if(fs.statSync(s).isDirectory())await this.#buildInternal([...r,l],n,e);else{s=fs.readFileSync(s);let t=s,i=!1;var o=(o=l.split("."))[o.length-1];try{var a=this.buildHandlers[o];if(a&&a.length)for(const c of a)await c(l,t,e=>t=e,e,o,r)}catch(e){printer.dev.fail("Failed to build: "+path.join(...r,l)),printer.dev.error(e),n[0]++,i=!0}e.file("source/"+r.map(e=>e+"/").join("")+l,t),config.includeOriginalInBuild&&e.file("original/"+r.join("/"),s),i||printer.dev.debug("Built "+path.join(...r,l))}}}async build(){if(!this.dev||argv.force){this.#isBuilding&&await this.#buildPromise,this.#isBuilding=!0;let t;if(this.#buildPromise=new Promise(e=>t=e),fs.existsSync(path.join(this.#dir,config.srcFolder))){var e=Date.now(),i=[0],r=new(require("jszip")),n=(await this.#buildInternal([],i,r),r.file("time",Date.now()+""),r.file("runtime",runtimeId+""),r.file("importMap",JSON.stringify(this.#importMap)),path.join(this.#dir,config.srcFolder,config.main)),n=this.jsxToJS(fs.readFileSync(n),n);if(n instanceof Error)return exit("Couldn't build the main file!",n);if(r.file("main",n),this.#firstBuild){this.#firstBuild=!1;var n=path.join(this.#dir,config.srcFolder,config.main),s=path.extname(n),o=[".jsx",".tsx"];if(!o.includes(s))return exit("Invalid file extension for the main file: "+s+", expected: "+o.join(" or "));if(!fs.statSync(n).isFile())return exit("Main file not found: "+n)}fs.writeFileSync(path.join(this.#dir,".build"),await r.generateAsync({type:"nodebuffer"}));s=Date.now()-e;0===i[0]?printer.dev.pass("Built. (%c"+timeForm(s)+"&t)","color: orange"):printer.dev.fail("Built with %c"+i[0]+"&t error"+(1<i[0]?"s":"")+". (%c"+timeForm(s)+"&t)","color: blue","color: blue")}else printer.dev.warn("Skipping building since there is no %c/"+config.srcFolder+"&t folder...","color: orange");this.#isBuilding=!1,t(),this.#buildCache||argv.build||await this.scanBuild()}}async scanBuild(){if(!this.dev){this.#isBuilding&&await this.waitBuild(),this.#isScanningBuild&&await this.waitBuildScanning(),fs.existsSync(path.join(this.#dir,".build"))||await this.build(),this.#isScanningBuild=!0,this.#buildCache={},this.#jsxCache={},this.#builtJSXCache={},this.#builtJSXPage={};let t;this.#scanPromise=new Promise(e=>t=e);var n=Date.now(),s=new(require("jszip"));await s.loadAsync(fs.readFileSync(path.join(this.#dir,".build")));let e,i,r;for(const d in s.files){var o=s.files[d];if(!o.dir){var a=await o.async("nodebuffer");if("time"===d)e=+a.toString();else if("runtime"===d)i=a.toString();else if("main"===d)this.#firstScan&&(this.#firstScan=!0,r=a);else if("importMap"===d)this.#importMap=JSON.parse(a.toString());else{var l=d.split("/")[0],o=this.scanHandlers[l];if(o){var c=d.split(".");let e=c[c.length-1];c=(e="__default__"===e?null:e)&&o[e]||o.__default__;if(c&&c.length)for(const u of c)await u(d.substring(l.length+1),a,s.files)}}}}return e?i?(n=Date.now()-n,printer.dev.pass("Scanned the build. (%c"+timeForm(n)+"&t)","color: orange"),this.#isScanningBuild=!1,this.#builtAt=e,this.#buildRuntimeId=i,r&&await this.processMain(r),t(),void(this.#listening||!config.listen||argv.build||await this.listen())):exit("Invalid build: No runtime ID found for the build! Try rebuilding."):exit("Invalid build: No timestamp found! Try rebuilding.")}!this.#listening&&config.listen&&await this.listen()}async#pseudoBuildJSX(t,e,i,r){let n=e;i||(i=await this.readClientJSX(t,e),n=i.code);const s=(this.#jsxFunctions[t]=i).clientFunctionList;return r.push(...await Promise.all(i.serverInit.map(async e=>(await runCodeAtSpecial(`${i.serverImportCode};${makeBeginCode(null,s,JSON.stringify(path.join(t)))};(${e.code})()`,[],path.join(this.#dir,config.srcFolder,t))).result.default||(e=>e)))),this.#buildCache||(this.#buildCache={}),this.#buildCache[t]=n,i}async processDevMain(){var e=path.join(this.#dir,config.srcFolder,config.main);await this.processMain(this.jsxToJS(fs.readFileSync(e),e))}async processMain(e){if("object"==typeof(e=e instanceof Buffer?e.toString():e))return printer.dev.error(e),process.exit();const t=global["R"+(this.#buildRuntimeId||runtimeId)]=(...e)=>require("preact").createElement(...e);Hizzy.Routes=global.Routes=()=>t("div",null),Hizzy.Route=global.Route=()=>t("div",null);let i;const r=path.join(this.#dir,config.srcFolder,config.main)+random()+"."+(config.mainModule?"m":"")+"js";var n=()=>{fs.existsSync(r)&&fs.rmSync(r,{recursive:!0})};try{fs.writeFileSync(r,e),i=await import(url.pathToFileURL(r))}catch(e){return n(),void printer.dev.error(e)}try{"function"==typeof this.#mainDoneCb&&await this.#mainDoneCb()}catch(e){printer.dev.error(e)}if(i&&i.onDone&&(this.#mainDoneCb=i.onDone),n(),!i||!(i=i.default))return exit("Expected a valid 'export default' from the main file.");if(i.type!==Routes)return exit("Expected the 'export default' from the main file to be a Routes component!");const a={},l=async(i,r={location:"",onRequest:[],allow:[],deny:[]})=>{if("object"!=typeof i||Array.isArray(i))for(const e of i)await l(e,r);else{if((i=i.type&&i.type!==Route&&i.type.isRouteParent?i.type(i.props,i.props.children):i).type!==Route)return exit("Expected every child component of the Routes component to be a Route component!");var n=path.join(r.location,i.props.path||"").replaceAll(path.sep,"/");if(i.props.children&&await l(i.props.children,{...r,location:n}),!i.props.path)return;if(a[n])return exit("Cannot add multiple routes to the same endpoint: "+n);var s=path.join(i.props.route||"");let e="*"===r.allow?"*":i.props.allow,t=("*"===(e=void 0===e?"auto":e)&&(r.allow=e),Array.isArray(e)&&(r.allow=[...new Set([...r.allow,...e])]),"*"===r.deny?"*":i.props.deny);"*"===(t=void 0===t?[]:t)&&(r.deny="*"),Array.isArray(t)&&(r.deny=[...new Set([...r.deny,...t])]);var o="Route '"+s+"'s 'allow' property is invalid, expected \"*\" or an array of strings, got: ";if("string"==typeof e){if("*"!==e&&"auto"!==e)return exit(o,e)}else if("object"!=typeof e||!Array.isArray(e)||e.some(e=>"string"!=typeof e))return exit(o,e);o="Route '"+s+"'s 'deny' property is invalid, expected \"*\" or an array of strings, got: ";if("string"==typeof t){if("*"!==t)return exit(o,t)}else if("object"!=typeof t||!Array.isArray(t)||t.some(e=>"string"!=typeof e))return exit(o,t);void(a[n]={route:s,routeJSON:JSON.stringify(s.replaceAll("\\","/")),allow:e,deny:t,onRequest:i.props.onRequest,method:(i.props.method||"get").toLowerCase()})}};i.props.children&&await l(i.props.children),Object.freeze(a),this.routes=a;var s=["all","get","post","put","delete","patch","options","head"];this.app._router.stack=this.app._router.stack.filter(e=>!e.route);for(const url in this.routes){const{route:o,method:c,routeJSON:d,allow:u,deny:h,onRequest:p}=this.routes[url];s.includes(c)?this.app[c](url,async(i,r,t)=>{i._Route=o,i._RouteJSON=d,i._Allow=u,i._Deny=h;let n=async(e=!1)=>{if(e)return t();this.dev?this.#devRender(o,i,r):await this.#buildRender(o,i,r)};if("function"==typeof p)p(i,r,n);else if("object"==typeof p&&Array.isArray(p)){const s=(t,...e)=>{if(t===p.length)return n();p[s](i,r,(...e)=>s(t+1,...e),...e)};await s(0)}else await n()}):printer.dev.warn("Invalid method: "+c+", expected one of these: "+s.join(", "))}this.app.get("*",(e,t)=>this.#staticRender(e,t))}async readClientJSX(e,t){const c={code:"",serverFunctions:{},clientFunctionList:[],serverInit:[],joinEvent:[],leaveEvent:[],importList:[],fileImportList:[],serverImportCode:"",functionIdentifiers:{}};if(e!==config.main){const i=this.jsxToJS(t,path.join(this.#dir,config.srcFolder,e),!0);if(i instanceof Error)throw i;t=babelParser.parse(i,{sourceType:"module"});const s=({start:e,end:t})=>i.substring(e,t),d=e=>{let t=0;for(;e&&e.node&&"Program"!==e.node.type;)"FunctionDeclaration"===e.node.type&&t++,e=e.parentPath;return t},u=e=>{const t=[];return e.traverse({Identifier(e){e.node._isMember||t.includes(e.node.name)||t.push(e.node.name)},MemberExpression(e){e.node.property._isMember=!0}}),t},o=(e,t,i,r)=>{var n=[];for(const a of e||[])for(const l of a.value.split("\n")){var s,o=l.replaceAll("*","").trim();"@client"===o?n.push(o):(s=this.functionDecorators[o])&&(n.push(o),s({name:t,leadingComments:e,code:i,json:c,pth:r,getIdentifiers:u,getDepth:d}))}n.some(e=>e.startsWith("@server"))||this.functionDecorators["@client"]({name:t,leadingComments:e,code:i,json:c,pth:r,getIdentifiers:u,getDepth:d})},r=(e,t)=>{"StringLiteral"===e.type&&(null!==this.#getPackageImport(e.value)?c.importList.includes(e.value)||(c.importList.push(e.value),t&&(c.serverImportCode+=t)):c.fileImportList.includes(e.value)||c.fileImportList.push(e.value))};c.after=[],traverse(t,{FunctionDeclaration:e=>{var{leadingComments:t,id:i}=e.node;i&&o(t,i.name,s(e.node),e)},VariableDeclaration:e=>{var{declarations:t,leadingComments:i}=e.node;if(t)for(const n of t){var r=n["init"];r&&["ArrowFunctionExpression","FunctionExpression"].includes(r.type)&&o(i,n.id.name,"FunctionExpression"===r.type?s(n):`(()=>${s(n).split("=").slice(1).join("=")})()`,e)}},CallExpression(e){var{callee:t,arguments:i}=e.node;"Identifier"===t.type&&"require"===t.name&&1===i.length&&(c.after.push(()=>e.replaceWith({type:"AwaitExpression",argument:{type:"CallExpression",callee:e.node.callee,arguments:e.node.arguments}})),r(i[0]))}}),c.after.forEach(e=>e()),c.after=[],c.clientFunctionList=[...new Set(c.clientFunctionList)];e=babelGenerator.default(t).code,t=this.dev?e:require("uglify-js").minify(e,{module:!0,compress:{toplevel:!0},mangle:!0});if(t.error)throw t.error;c.code="string"==typeof t?t:t.code}return c}#getPackageImport(e){if(e=e.split("?")[0].split("#")[0],this.#importMap[e])return this.#importMap[e];if(e.includes(".")||["hizzy","@hizzyjs/types","react","preact"].includes(e)||this.getAddonByName(e))return null;var t=path.join(this.#dir,"node_modules",e);if(!fs.existsSync(t)||!fs.statSync(t).isDirectory())return null;var i=path.join(t,"package.json");if(!fs.existsSync(i)||!fs.statSync(i).isFile())return null;i=require(i);const r=this.#importMap[e]={code:esbuild.buildSync({stdin:{contents:"export * as default from "+JSON.stringify(e),resolveDir:this.#dir,sourcefile:".js",loader:"ts"},bundle:!0,minify:!0,format:"esm",write:!1}).outputFiles[0].text,version:i.version||"",actual:void 0};return r.actual=import(url.pathToFileURL(path.join(t,i.main))),r.actual.then(e=>r.actual=e),r}async waitBuild(){return this.#buildPromise}async waitBuildScanning(){return this.#scanPromise}async sendEvalTo(e,t){e=this.#clients[e];if(!e)return!1;var i=this.#evalId++;e._send(SERVER2CLIENT.CLIENT_FUNCTION_REQUEST+i+":"+t);let r;e=new Promise(e=>r=e),this.#evalResponses[i]=r,t=await e;return delete this.#evalResponses[i],t}clientUUIDs(){return Object.keys(this.#clients)}async broadcastEval(e){var t={};for(const i of this.clientUUIDs())t[i]=await this.sendEvalTo(i,e);return t}getHash(e){return this.#hashes[e]||null}findClient(e){e=this.#clients[e];return e?new Client(e):null}findSocket(e){return this.#clients[e]||null}get directory(){return this.#dir}makeClientFunction(e,t,i=null,r=null){return makeClientFunction(e,t,i,r)}getAddons(){return Addon.addons}getAddon(e){return Addon.addons[e]||null}getAddonByName(t){return Object.keys(Addon.addons).find(e=>Addon.addons[e].module.name===t)}jsxToJS(e,t,i=!1){try{return babel.transformSync(e,{filename:t,presets:[[require("@babel/preset-react"),{pragma:"R"+runtimeId,pragmaFrag:"F"+runtimeId}],...t.endsWith(".tsx")?[require("@babel/preset-typescript")]:[]],plugins:[...i?[require("@babel/plugin-transform-export-namespace-from"),require("@babel/plugin-transform-modules-commonjs")]:[]]}).code}catch(e){return e}}tsToJS(e){try{return babel.transformSync(e,{filename:"file.ts",presets:[require("@babel/preset-typescript")]}).code}catch(e){return e}}getCookie(e,t){e=(e||"").split(";").map(e=>e.trim()).find(e=>e.startsWith(t+"="));return e?e.substring(t.length+1):null}useGlobalState(t,e){t=t||"",this.#globalStates.has(t)||this.#globalStates.set(t,e);const i=()=>this.#globalStates.get(t);return{get:i,set:e=>{"function"==typeof e&&(e=e(i())),this.#globalStates.set(t,e)},delete:()=>this.#globalStates.delete(t)}}useCooldown(e,t,{amount:i,time:r}){if(e=e||"","number"!=typeof i||"number"!=typeof r)throw new Error("useCooldown() function requires an object that includes 'amount' and 'time' as numeric properties. It will check if the client has run this part of the code 'amount' times in the last 'time' milliseconds.");"string"!=typeof t&&(t=t.ip);var{get:e,set:t}=Hizzy.useGlobalState(e+"-Cooldown-Hizzy-Internal-"+t,[0]),e=e().filter(e=>Date.now()<e);return!(e.length>i||(e.push(Date.now()+r),t(e),0))}defineConfig(e){return e||{}}getPkg(e){return(this.#getPackageImport(e)||{}).actual}minify=minify}module.exports=API;