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"; const Transpiled = new Map(); /** * checks for (.tsx | .jsx | .ts | .js) extensions */ export 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; }; export const Transpile =async(inPath:string, inKey:string):Promise=> { const body = await Deno.readTextFile(inPath); const transpile = await ESBuild.transform(body, { loader: "tsx", sourcemap: "inline", minify:true }); Transpiled.set(inKey, transpile.code); return transpile.code; }; let ImportString = ``; let ImportObject = {}; try { const confDeno = await Deno.readTextFile(Deno.cwd()+"/deno.json"); const confDenoParsed:{importMap?:string, imports?:string} = JSON.parse(confDeno); if(confDenoParsed.importMap) { try { const confImports = await Deno.readTextFile(confDenoParsed.importMap); try { ImportObject = JSON.parse(confImports); ImportString = 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}; ImportString = JSON.stringify(ImportObject); } } catch(e) { console.log(`deno.json not found`); } const Index = `
Loading
`; Deno.serve({ port: 3000 }, async(_req:Request) => { const url:URL = new URL(_req.url); const fsPath = Deno.cwd()+url.pathname; 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 = Index; // serve .tsx .jsx .ts .js if(Transpileable(url.pathname)) { type = `application/javascript`; if(!url.searchParams.get("reload")) { const path = `file://${Deno.cwd().replaceAll("\\", "/")+url.pathname}`; console.log(path); const imp = await import(path); const members = []; for( const key in imp ) { members.push(key); } body = `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") } }; window.HMR("${url.pathname}", reloadHandler);`; } else { body = Transpiled.get(url.pathname) || await Transpile(fsPath, url.pathname); } } // serve static media else if( url.pathname.endsWith("/") === false) { body = await Deno.readFile(fsPath); type = MIME.typeByExtension(url.pathname.substring(url.pathname.lastIndexOf("."))) || "text/html"; } return new Response(body, {headers:{"content-type":type as string}}); } catch(error) { console.log(` ...404`); return new Response(error, {status:404}); } }); 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("Files changed...") for await (const [file, action] of FilesChanged) { const pathname = file.substring(Deno.cwd().length).replaceAll("\\", "/"); console.log(pathname, action); if(Transpileable(pathname)) { if(action !== "remove") { await Transpile(file, pathname); console.log(` ...cached "${pathname}"`); SocketsBroadcast(pathname); } } } FilesChanged.clear(); }, 1000); for await (const event of Deno.watchFs(Deno.cwd())) { event.paths.forEach( path => FilesChanged.set(path, event.kind) ); ProcessFiles(); }