eno/server.tsx

291 lines
8.2 KiB
TypeScript

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();
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<string>=>
{
const transpile = await ESBuild.transform(inCode, { loader: "tsx", sourcemap: "inline", minify:true });
Transpiled.set(inKey, transpile.code);
return transpile.code;
};
type Transpiler = (inPath:string, inKey:string, inCheck?:boolean)=>Promise<string>;
const TranspileFS:Transpiler =async(inPath, inKey, inCheck)=>
{
if(inCheck)
{
const cached = Transpiled.get(inKey);
if(cached)
{
return cached;
}
}
const body = await Deno.readTextFile(inPath);
return Transpile(body, inKey);
};
const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=>
{
if(inCheck)
{
const cached = Transpiled.get(inKey);
if(cached)
{
return cached;
}
}
const path = import.meta.resolve(`.${inPath}`);
let body = await fetch(path);
let text = await body.text();
return Transpile(text, inKey);
};
const LibPath = "lib";
type ImportMap = {imports?:Record<string, string>, importMap?:string};
let ImportString = ``;
let ImportObject:ImportMap = {};
try
{
const confDeno = await Deno.readTextFile(Deno.cwd()+"/deno.json");
const confDenoParsed:ImportMap = 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);
}
if(ImportObject.imports)
{
const importReact = ImportObject.imports?.["react"];
if(importReact)
{
ImportObject.imports["react-original"] = importReact;
ImportObject.imports["react"] = `./${LibPath}/react.tsx`;
ImportString = JSON.stringify(ImportObject);
}
else
{
console.log(`"imports" configuration does not alias "react"`);
}
}
else
{
console.log(`No "imports" found in configuration`);
}
}
catch(e)
{
console.log(`deno.json not found`);
}
const Index = `
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="importmap">${ImportString}</script>
<script async src="https://ga.jspm.io/npm:es-module-shims@1.5.1/dist/es-module-shims.js" crossorigin="anonymous"></script>
</head>
<body>
<div id="app">Loading</div>
<script type="module">
import * as TW from "https://esm.sh/@twind/core@1.0.1";
import TWPreTail from "https://esm.sh/@twind/preset-tailwind@1.0.1";
import TWPreAuto from "https://esm.sh/@twind/preset-autoprefix@1.0.1";
const Configure = {presets: [TWPreTail(), TWPreAuto()]};
const ShadowDOM = document.querySelector("#app").attachShadow({mode: "open"});
const ShadowDiv = document.createElement("div");
const ShadowCSS = document.createElement("style");
ShadowDOM.append(ShadowCSS);
ShadowDOM.append(ShadowDiv);
TW.observe(TW.twind(Configure, TW.cssom(ShadowCSS)), ShadowDiv);
import App from "./app.tsx";
import {render, createElement as H} from "react";
render(H(()=>H(App)), ShadowDiv);
</script>
</body>
</html>
`;
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;
const isLib = url.pathname.startsWith(`/${LibPath}/`)
// serve .tsx .jsx .ts .js
if(Transpileable(url.pathname))
{
type = `application/javascript`;
if(isLib)
{
body = await TranspileURL(url.pathname, url.pathname, true);
}
else 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 {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 TranspileFS(fsPath, url.pathname, true);
}
}
// serve static media
else if( url.pathname.endsWith("/") === false)
{
type = MIME.typeByExtension(url.pathname.substring(url.pathname.lastIndexOf("."))) || "text/html";
if(isLib)
{
const _fetch = await fetch(import.meta.resolve(`.${url.pathname}`));
body = await _fetch.text();
}
else
{
body = await Deno.readFile(fsPath);
}
}
return new Response(body, {headers:{"content-type":type as string}});
}
catch(error)
{
console.log(error);
return new Response(error, {status:404});
}
});
const Sockets:Set<WebSocket> = new Set();
const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } }
const FilesChanged:Map<string, string> = 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 TranspileFS(path, 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();
}
}