import * as ESBuild from 'https://deno.land/x/esbuild@v0.14.45/mod.js'; import * as MIME from "https://deno.land/std@0.180.0/media_types/mod.ts"; import { debounce } from "https://deno.land/std@0.151.0/async/debounce.ts"; import SSR from "https://esm.sh/v113/preact-render-to-string@6.0.2"; import * as Twind from "https://esm.sh/@twind/core@1.1.3"; import React from "react"; import * as Iso from "@eno/iso"; let hosted = import.meta.resolve("./"); const Path = { Hosted:hosted.substring(0, hosted.length-1), Active:`file://${Deno.cwd().replaceAll("\\", "/")}` }; console.log(Path); const Transpiled = new Map(); const Transpileable =(inFilePath:string):boolean=> { let dotIndex = inFilePath.length-4; if(inFilePath[dotIndex] !== ".") { if(inFilePath[++dotIndex] !== ".") { return false; } } if(inFilePath[dotIndex+2] == "s") { const first = inFilePath[dotIndex+1]; return (first == "t" || first == "j"); } return false; }; const Transpile =async(inCode:string, inKey:string):Promise=> { const transpile = await ESBuild.transform(inCode, { loader: "tsx", minify:true}); Transpiled.set(inKey, transpile.code); return transpile.code; }; type Transpiler = (inPath:string, inKey:string, inCheck?:boolean)=>Promise; const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=> { if(inCheck) { const cached = Transpiled.get(inKey); if(cached) { return cached; } } let body = await fetch(inPath); let text = await body.text(); return Transpile(text, inKey); }; const LibPath = "lib"; type ImportMap = {imports?:Record, importMap?:string}; let ImportObject:ImportMap = {}; try { const confDeno = await fetch(`${Path.Active}/deno.json`); const confDenoParsed:ImportMap = await confDeno.json(); if(confDenoParsed.importMap) { try { const confImports = await Deno.readTextFile(confDenoParsed.importMap); try { ImportObject = JSON.parse(confImports); } catch(e) { console.log(`"importMap" "${confDenoParsed.importMap}" contains invalid JSON`); } } catch(e) { console.log(`"importMap" "${confDenoParsed.importMap}" cannot be found`); } } else if(confDenoParsed.imports) { ImportObject = {imports:confDenoParsed.imports}; } if(ImportObject.imports) { const importReact = ImportObject.imports["react"]; if(importReact) { ImportObject.imports["react-original"] = importReact; ImportObject.imports["react"] = `/${LibPath}/react.tsx`; } else { console.log(`"imports" configuration does not alias "react"`); } const importApp = ImportObject.imports["@eno/app"]; if(importApp) { } else { console.log(`"imports" configuration does not alias an entry-point component with "@eno/app"`); } const importIso = ImportObject.imports["@eno/iso"]; if(importIso) { ImportObject.imports["@eno/iso"] = `/${LibPath}/iso.tsx`; } else { } Object.entries(ImportObject.imports).forEach(([key, value])=>{ if(value.startsWith("./") && ImportObject.imports) { ImportObject.imports[key] = value.substring(1); } }) } else { console.log(`No "imports" found in configuration`); } } catch(e) { console.log(`deno.json not found`); } Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) => { const url:URL = new URL(_req.url); const pathParts = url.pathname.substring(1, url.pathname.endsWith("/") ? url.pathname.length-1 : url.pathname.length).split("/"); const pathLast = pathParts.at(-1); const pathExt:string|undefined = pathLast?.split(".")[1]; console.log(pathParts, pathLast, pathExt); console.log(`Request for "${url.pathname}"...`); if(_req.headers.get("upgrade") == "websocket") { try { const { response, socket } = Deno.upgradeWebSocket(_req); socket.onopen = () => { Sockets.add(socket); console.log("Overwatch: Socket created"); }; socket.onclose = () => { Sockets.delete(socket); console.log("Overwatch: Socket deleted"); }; socket.onmessage = (e) => {}; socket.onerror = (e) => console.log("Overwatch: Socket errored:", e); return response; } catch(e) { // } } try { // serve index by default let type = `text/html`; let body:BodyInit = ``; const isLib = url.pathname.startsWith(`/${LibPath}/`); if(Transpileable(url.pathname)) { type = `application/javascript`; if(isLib) { body = await TranspileURL(Path.Hosted+url.pathname, url.pathname, true); } else if(!url.searchParams.get("reload")) { const imp = await import(Path.Active+url.pathname); const members = []; for( const key in imp ) { members.push(key); } body = ` import {FileListen} from "/${LibPath}/hmr.tsx"; import * as Import from "${url.pathname}?reload=0"; ${ members.map(m=>`let proxy_${m} = Import.${m}; export { proxy_${m} as ${m} }; `).join(" ") } const reloadHandler = (updatedModule)=> { ${ members.map(m=>`proxy_${m} = updatedModule.${m};`).join("\n") } }; FileListen("${url.pathname}", reloadHandler);`; } else { body = await TranspileURL(Path.Active+url.pathname, url.pathname, true); } } // serve static media else if( pathExt ) { type = MIME.typeByExtension(pathExt) || "text/html"; const _fetch = await fetch((isLib ? Path.Hosted : Path.Active)+url.pathname); body = await _fetch.text(); } else { const results = Twind.extract(SSR(), TwindInst); type = `text/html`; body = ` ${Iso.Meta.title}
${results.html}
`; } return new Response(body, {headers:{"content-type":type as string, "Access-Control-Allow-Origin":"*", charset:"utf-8"}}); } catch(error) { console.log(error); return new Response(error, {status:404}); } }); import App, {CSS} from "@eno/app"; const TwindInst = Twind.install(CSS); const Sockets:Set = new Set(); const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } } const FilesChanged:Map = new Map(); const ProcessFiles =debounce(async()=> { console.log("Processing Files...", FilesChanged); for await (const [path, action] of FilesChanged) { const key = path.substring(Deno.cwd().length).replaceAll("\\", "/"); console.log(key, action); if(action != "remove") { await TranspileURL(Path.Active+key, key, false); console.log(` ...cached "${key}"`); SocketsBroadcast(key); } else { Transpiled.delete(key); } } FilesChanged.clear(); }, 1000); for await (const event of Deno.watchFs(Deno.cwd())) { event.paths.forEach( path => { if(Transpileable(path)) { FilesChanged.set(path, event.kind); } }); if(FilesChanged.size) { ProcessFiles(); } }