eno/server.tsx

316 lines
8.9 KiB
TypeScript
Raw Permalink Normal View History

2023-03-16 08:25:44 -04:00
import * as ESBuild from 'https://deno.land/x/esbuild@v0.14.45/mod.js';
2023-03-17 11:54:36 -04:00
import * as MIME from "https://deno.land/std@0.180.0/media_types/mod.ts";
2022-12-01 17:10:59 -05:00
import { debounce } from "https://deno.land/std@0.151.0/async/debounce.ts";
2023-04-02 14:16:46 -04:00
import SSR from "https://esm.sh/v113/preact-render-to-string@6.0.2";
2023-04-05 20:05:21 -04:00
import * as Twind from "https://esm.sh/@twind/core@1.1.3";
import React, {JSX, createElement as h} from "react";
2023-04-06 23:44:27 -04:00
import * as Iso from "@eno/iso";
2023-03-17 11:54:36 -04:00
const Transpiled = new Map();
2023-04-01 08:44:39 -04:00
const Transpileable =(inFilePath:string):boolean=>
2022-12-01 17:10:59 -05:00
{
2023-03-17 11:54:36 -04:00
let dotIndex = inFilePath.length-4;
if(inFilePath[dotIndex] !== ".")
{
if(inFilePath[++dotIndex] !== ".")
{
return false;
}
}
2022-12-01 17:10:59 -05:00
2023-03-17 11:54:36 -04:00
if(inFilePath[dotIndex+2] == "s")
{
const first = inFilePath[dotIndex+1];
return (first == "t" || first == "j");
}
return false;
};
2023-04-01 08:44:39 -04:00
const Transpile =async(inCode:string, inKey:string):Promise<string>=>
2022-12-01 17:10:59 -05:00
{
2023-03-27 23:05:20 -04:00
const transpile = await ESBuild.transform(inCode, { loader: "tsx", sourcemap: "inline", minify:true });
2022-12-01 17:10:59 -05:00
Transpiled.set(inKey, transpile.code);
return transpile.code;
};
2023-03-27 23:05:20 -04:00
type Transpiler = (inPath:string, inKey:string, inCheck?:boolean)=>Promise<string>;
2023-04-01 08:44:39 -04:00
const TranspileFS:Transpiler =async(inPath, inKey, inCheck)=>
2023-03-27 23:05:20 -04:00
{
if(inCheck)
{
const cached = Transpiled.get(inKey);
if(cached)
{
return cached;
}
}
const body = await Deno.readTextFile(inPath);
return Transpile(body, inKey);
};
2023-04-01 08:44:39 -04:00
const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=>
2023-03-27 23:05:20 -04:00
{
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);
};
2022-12-01 17:10:59 -05:00
2023-04-01 08:44:39 -04:00
const LibPath = "lib";
2023-03-22 17:45:25 -04:00
type ImportMap = {imports?:Record<string, string>, importMap?:string};
let ImportObject:ImportMap = {};
2023-03-17 11:54:36 -04:00
try
{
const confDeno = await Deno.readTextFile(Deno.cwd()+"/deno.json");
2023-03-22 17:45:25 -04:00
const confDenoParsed:ImportMap = JSON.parse(confDeno);
2023-03-17 11:54:36 -04:00
if(confDenoParsed.importMap)
{
try
{
const confImports = await Deno.readTextFile(confDenoParsed.importMap);
try
{
ImportObject = JSON.parse(confImports);
}
catch(e)
{
2023-03-22 17:45:25 -04:00
console.log(`"importMap" "${confDenoParsed.importMap}" contains invalid JSON`);
2023-03-17 11:54:36 -04:00
}
}
catch(e)
{
2023-03-22 17:45:25 -04:00
console.log(`"importMap" "${confDenoParsed.importMap}" cannot be found`);
2023-03-17 11:54:36 -04:00
}
}
else if(confDenoParsed.imports)
{
ImportObject = {imports:confDenoParsed.imports};
}
2023-03-22 17:45:25 -04:00
if(ImportObject.imports)
{
2023-04-01 15:34:50 -04:00
const importReact = ImportObject.imports["react"];
2023-03-22 17:45:25 -04:00
if(importReact)
{
ImportObject.imports["react-original"] = importReact;
2023-04-07 21:36:51 -04:00
ImportObject.imports["react"] = `/${LibPath}/react.tsx`;
2023-03-22 17:45:25 -04:00
}
else
{
console.log(`"imports" configuration does not alias "react"`);
}
2023-04-01 15:34:50 -04:00
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)
{
2023-04-07 21:36:51 -04:00
ImportObject.imports["@eno/iso"] = `/${LibPath}/iso.tsx`;
}
else
{
}
2023-04-07 21:36:51 -04:00
Object.entries(ImportObject.imports).forEach(([key, value])=>{
if(value.startsWith("./") && ImportObject.imports)
{
ImportObject.imports[key] = value.substring(1);
}
})
2023-03-22 17:45:25 -04:00
}
else
{
console.log(`No "imports" found in configuration`);
}
2023-03-17 11:54:36 -04:00
}
catch(e)
{
console.log(`deno.json not found`);
}
2023-03-31 06:55:54 -04:00
2023-04-02 14:16:46 -04:00
2023-04-05 20:05:21 -04:00
Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) =>
2022-12-01 17:10:59 -05:00
{
const url:URL = new URL(_req.url);
const fsPath = Deno.cwd()+url.pathname;
2023-04-07 21:36:51 -04:00
const pathParts = url.pathname.substring(1, url.pathname.endsWith("/") ? url.pathname.length-1 : url.pathname.length).split("/");
const pathLast = pathParts[pathParts.length-1];
const pathExt:string|undefined = pathLast.split(".")[1];
console.log(pathParts, pathLast, pathExt);
2022-12-01 17:10:59 -05:00
console.log(`Request for "${url.pathname}"...`);
2023-03-20 17:41:57 -04:00
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)
{
//
}
}
2022-12-01 17:10:59 -05:00
try
{
2023-03-17 11:54:36 -04:00
// serve index by default
let type = `text/html`;
2023-04-01 22:45:33 -04:00
let body:BodyInit = ``;
2023-03-17 11:54:36 -04:00
2023-04-07 21:36:51 -04:00
const isLib = url.pathname.startsWith(`/${LibPath}/`);
2023-03-27 23:05:20 -04:00
2023-04-07 21:36:51 -04:00
if(Transpileable(pathLast))
2022-12-01 17:10:59 -05:00
{
2023-03-27 23:05:20 -04:00
type = `application/javascript`;
if(isLib)
2022-12-01 17:10:59 -05:00
{
2023-03-27 23:05:20 -04:00
body = await TranspileURL(url.pathname, url.pathname, true);
}
else if(!url.searchParams.get("reload"))
{
const path = `file://${Deno.cwd().replaceAll("\\", "/")+url.pathname}`;
const imp = await import(path);
const members = [];
for( const key in imp ) { members.push(key); }
body =
2023-03-31 06:55:54 -04:00
`
2023-04-01 08:44:39 -04:00
import {FileListen} from "/${LibPath}/hmr.tsx";
2023-03-31 06:55:54 -04:00
import * as Import from "${url.pathname}?reload=0";
${ members.map(m=>`let proxy_${m} = Import.${m};
export { proxy_${m} as ${m} };
`).join(" ") }
2023-03-27 23:05:20 -04:00
const reloadHandler = (updatedModule)=>
{
${ members.map(m=>`proxy_${m} = updatedModule.${m};`).join("\n") }
};
2023-03-31 06:55:54 -04:00
FileListen("${url.pathname}", reloadHandler);`;
2023-03-22 17:45:25 -04:00
2023-03-20 17:41:57 -04:00
}
2023-03-27 23:05:20 -04:00
else
{
body = await TranspileFS(fsPath, url.pathname, true);
}
}
// serve static media
2023-04-07 21:36:51 -04:00
else if( pathExt )
2023-03-27 23:05:20 -04:00
{
2023-04-07 21:36:51 -04:00
type = MIME.typeByExtension(pathExt) || "text/html";
2023-03-27 23:05:20 -04:00
if(isLib)
{
const _fetch = await fetch(import.meta.resolve(`.${url.pathname}`));
body = await _fetch.text();
}
else
2023-03-20 17:41:57 -04:00
{
2023-03-22 17:45:25 -04:00
body = await Deno.readFile(fsPath);
2022-12-01 17:10:59 -05:00
}
}
2023-04-01 22:45:33 -04:00
else
{
const results = Twind.extract(SSR(<App/>), TwindInst);
2023-04-02 14:16:46 -04:00
2023-04-01 22:45:33 -04:00
type = `text/html`;
body = `<!doctype html>
2023-04-06 23:44:27 -04:00
<html lang="en">
2023-04-01 22:45:33 -04:00
<head>
2023-04-06 23:44:27 -04:00
<title>${Iso.Meta.title}</title>
2023-04-01 22:45:33 -04:00
<meta name="viewport" content="width=device-width, initial-scale=1.0">
2023-04-06 23:44:27 -04:00
<meta charset="utf-8"/>
2023-04-02 14:16:46 -04:00
<style data-twind>${results.css}</style>
2023-04-01 22:45:33 -04:00
<script type="importmap">${JSON.stringify(ImportObject)}</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>
2023-04-02 14:16:46 -04:00
<div id="app">${results.html}</div>
2023-04-01 22:45:33 -04:00
<script type="module">
import {render, createElement as H} from "react";
import * as Twind from "https://esm.sh/@twind/core@1.1.3";
import {default as App, CSS} from "@eno/app";
Twind.install(CSS);
render(H(()=>H(App)), document.querySelector("#app"));
2023-04-01 22:45:33 -04:00
</script>
</body>
</html>`;
}
2022-12-01 17:10:59 -05:00
2023-04-06 23:44:27 -04:00
return new Response(body, {headers:{"content-type":type as string, "Access-Control-Allow-Origin":"*", charset:"utf-8"}});
2022-12-01 17:10:59 -05:00
}
catch(error)
{
console.log(error);
2022-12-01 17:10:59 -05:00
return new Response(error, {status:404});
}
});
2023-04-05 20:05:21 -04:00
import App, {CSS} from "@eno/app";
const TwindInst = Twind.install(CSS);
2023-03-17 11:54:36 -04:00
const Sockets:Set<WebSocket> = new Set();
const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } }
2023-03-20 17:41:57 -04:00
2023-03-17 11:54:36 -04:00
const FilesChanged:Map<string, string> = new Map();
2022-12-01 17:10:59 -05:00
const ProcessFiles =debounce(async()=>
{
2023-04-01 10:27:24 -04:00
console.log("Processing Files...", FilesChanged);
for await (const [path, action] of FilesChanged)
2022-12-01 17:10:59 -05:00
{
2023-04-01 10:27:24 -04:00
const key = path.substring(Deno.cwd().length).replaceAll("\\", "/");
console.log(key, action);
if(action != "remove")
2022-12-01 17:10:59 -05:00
{
2023-04-01 10:27:24 -04:00
await TranspileFS(path, key, false);
console.log(` ...cached "${key}"`);
SocketsBroadcast(key);
}
else
{
2023-04-05 20:05:21 -04:00
Transpiled.delete(key);
2022-12-01 17:10:59 -05:00
}
}
2023-03-17 11:54:36 -04:00
FilesChanged.clear();
2022-12-01 17:10:59 -05:00
}, 1000);
2023-03-17 11:54:36 -04:00
for await (const event of Deno.watchFs(Deno.cwd()))
2022-12-01 17:10:59 -05:00
{
2023-04-01 10:27:24 -04:00
event.paths.forEach( path =>
{
if(Transpileable(path))
{
FilesChanged.set(path, event.kind);
}
});
if(FilesChanged.size)
{
ProcessFiles();
}
2022-12-01 17:10:59 -05:00
}