boot-function #1

Merged
SethTrowbridge merged 25 commits from boot-function into master 2023-06-21 07:53:14 -04:00
2 changed files with 148 additions and 86 deletions
Showing only changes of commit c758f66b27 - Show all commits

View File

@ -1,19 +1,32 @@
import * as HTTP from "https://deno.land/std@0.177.0/http/server.ts"; import Setup, {Transpile, Extension} from "./serve.tsx";
import Setup, {Transpile} from "./serve.tsx";
const Directory = `file://${Deno.cwd().replaceAll("\\", "/")}`;
Transpile.Config.sourceMaps = "inline";
Setup({Proxy:Directory});
const SocketsLive:Set<WebSocket> = new Set(); const SocketsLive:Set<WebSocket> = new Set();
const SocketsSend =(inData:string)=>{ console.log(inData); for (const socket of SocketsLive){ socket.send(inData); } } const SocketsSend =(inData:string)=>{ console.log(inData); for (const socket of SocketsLive){ socket.send(inData); } }
HTTP.serve((_req:Request)=> const Directory = `file://${Deno.cwd().replaceAll("\\", "/")}`;
{
if(_req.headers.get("upgrade") == "websocket") Setup({
Proxy:Directory,
SWCOp:
{
sourceMaps: "inline",
minify: false,
jsc:
{
target:"es2022",
parser:
{
syntax: "typescript",
tsx: true,
}
}
},
async Serve(inReq, inURL, inExt)
{
if(inReq.headers.get("upgrade") == "websocket")
{ {
try try
{ {
const { response, socket } = Deno.upgradeWebSocket(_req); const { response, socket } = Deno.upgradeWebSocket(inReq);
socket.onopen = () => SocketsLive.add(socket); socket.onopen = () => SocketsLive.add(socket);
socket.onclose = () => SocketsLive.delete(socket); socket.onclose = () => SocketsLive.delete(socket);
socket.onmessage = (e) => {}; socket.onmessage = (e) => {};
@ -25,8 +38,34 @@ HTTP.serve((_req:Request)=>
return new Response(e); return new Response(e);
} }
} }
return new Response(`websockets only`);
}, { port: 4444 }); if(!inExt)
{
await fetch(Directory+"/deno.json");
return new Response(
`<!doctype html>
<html>
<head>
</head>
<body>
<div id="app"></div>
<script type="importmap">
{
"imports":
{
"react":"https://esm.sh/preact/compat"
}
}
</script>
<script type="module"></script>
</body>
</html>`, {headers:{"content-type":"text/html"}});
}
return false;
}
});
let blocking = false; let blocking = false;
const filesChanged:Map<string, string> = new Map(); const filesChanged:Map<string, string> = new Map();
@ -39,11 +78,13 @@ for await (const event of Deno.watchFs(Deno.cwd()))
setTimeout(async()=> setTimeout(async()=>
{ {
for await (const [path, action] of filesChanged) for await (const [path, action] of filesChanged)
{
if(Transpile.Check(Extension(path)))
{ {
const key = path.substring(Deno.cwd().length).replaceAll("\\", "/"); const key = path.substring(Deno.cwd().length).replaceAll("\\", "/");
if(action != "remove") if(action != "remove")
{ {
const tsx = await Transpile.Fetch(Directory+key, key, true); const tsx = await Transpile.Fetch(Directory+key, key, true, true);
tsx && SocketsSend(key); tsx && SocketsSend(key);
} }
else else
@ -51,6 +92,7 @@ for await (const event of Deno.watchFs(Deno.cwd()))
Transpile.Cache.delete(key); Transpile.Cache.delete(key);
} }
} }
}
filesChanged.clear(); filesChanged.clear();
blocking = false; blocking = false;
} }

100
serve.tsx
View File

@ -2,19 +2,16 @@ import * as MIME from "https://deno.land/std@0.180.0/media_types/mod.ts";
import * as HTTP from "https://deno.land/std@0.177.0/http/server.ts"; import * as HTTP from "https://deno.land/std@0.177.0/http/server.ts";
import * as SWCW from "https://esm.sh/@swc/wasm-web@1.3.62"; import * as SWCW from "https://esm.sh/@swc/wasm-web@1.3.62";
export type Configuration = {Proxy:string, Allow:string, Reset:string, Local:boolean}; type CustomHTTPHandler = (inReq:Request, inURL:URL, inExtension:string|false)=>false|Response|Promise<Response|false>
export type ConfigurationArgs = {Proxy?:string, Allow?:string, Reset?:string, Local?:boolean}; type Configuration = {Proxy:string, Allow:string, Reset:string, SWCOp:SWCW.Options, Serve:CustomHTTPHandler};
export let Configure:Configuration = type ConfigurationArgs = {Proxy?:string, Allow?:string, Reset?:string, SWCOp?:SWCW.Options, Serve?:CustomHTTPHandler};
let Configure:Configuration =
{ {
Proxy: "", Proxy: "",
Allow: "*", Allow: "*",
Reset: "/clear-cache", Reset: "/clear-cache",
Local: false Serve: ()=>false,
}; SWCOp:
export default (config:ConfigurationArgs)=> Configure = {...Configure, ...config};
export const Transpile = {
Config:
{ {
sourceMaps: false, sourceMaps: false,
minify: true, minify: true,
@ -35,9 +32,19 @@ export const Transpile = {
{ {
react: { runtime: "automatic" } react: { runtime: "automatic" }
} }
}, }
} as SWCW.Options, }
};
export default (config:ConfigurationArgs)=> Configure = {...Configure, ...config};
export const Transpile =
{
Cache: new Map() as Map<string, string>, Cache: new Map() as Map<string, string>,
Files: ["tsx", "jsx", "ts", "js", "mjs"],
Check(inExtension:string|false)
{
return inExtension ? this.Files.includes(inExtension) : false;
},
Clear() Clear()
{ {
const size = this.Cache.size; const size = this.Cache.size;
@ -45,9 +52,6 @@ export const Transpile = {
return size; return size;
}, },
Fetch: async function(inPath:string, inKey:string, inCheckCache=true) Fetch: async function(inPath:string, inKey:string, inCheckCache=true)
{
console.log("transpile", inPath)
if(inPath.endsWith(".tsx") || inPath.endsWith(".jsx") || inPath.endsWith(".js") || inPath.endsWith(".mjs"))
{ {
const check = this.Cache.get(inPath); const check = this.Cache.get(inPath);
if(check && inCheckCache) if(check && inCheckCache)
@ -60,62 +64,78 @@ export const Transpile = {
{ {
const resp = await fetch(inPath); const resp = await fetch(inPath);
const text = await resp.text(); const text = await resp.text();
const {code} = await SWCW.transform(text, {...this.Config, filename:inKey}); const {code} = await SWCW.transform(text, { ...Configure.SWCOp, filename:inKey});
this.Cache.set(inKey, code); this.Cache.set(inKey, code);
return code; return code;
} }
catch(e) catch(e)
{ {
console.log(`xpile.tsx error. Key:${inKey} Path:${inPath} Error:"${e}"`); //console.log(`Transpile.Fetch error. Key:"${inKey}" Path:"${inPath}" Error:"${e}"`);
return null; return null;
} }
} }
} }
else };
{
return false; export const Extension =(inPath:string)=>
} {
} const posSlash = inPath.lastIndexOf("/");
const posDot = inPath.lastIndexOf(".");
return posDot > posSlash ? inPath.substring(posDot+1).toLowerCase() : false;
}; };
SWCW.default(); SWCW.default();
console.log("starting server");
HTTP.serve(async(req: Request)=> HTTP.serve(async(req: Request)=>
{ {
const url:URL = new URL(req.url); const url:URL = new URL(req.url);
const ext = Extension(url.pathname);
const headers = {"content-type":"application/json", "Access-Control-Allow-Origin": Configure.Allow, "charset":"UTF-8"};
if(url.pathname.endsWith("/")) // allow for custom handler
const custom = await Configure.Serve(req, url, ext);
if(custom)
{ {
return custom;
} }
// implied index.html files
if(!ext)
{
return new Response(`<!doctype html>
<html>
<head>
</head>
<body>
<script type="importmap"></script>
<script type="module"></script>
</body>
</html>`, {headers:{...headers, "content-type":"text/html"}});
}
// cache-reset route
if(url.pathname === Configure.Reset) if(url.pathname === Configure.Reset)
{ {
return new Response(`cache cleared (${Transpile.Clear()} items)`); return new Response(`{"cleared":${Transpile.Clear()}}`, {headers});
} }
// transpileable files
if(Transpile.Check(ext))
{
const lookup = await Transpile.Fetch(Configure.Proxy + url.pathname, url.pathname); const lookup = await Transpile.Fetch(Configure.Proxy + url.pathname, url.pathname);
if(lookup === null) return new Response(lookup, {status:lookup?200:404, headers:{...headers, "content-type":"application/javascript"}} );
{
// error
return new Response(`transpile error (see console)`, {status:404, headers:{"content-type":"application/javascript", "Access-Control-Allow-Origin": Configure.Allow, charset:"utf-8"}});
} }
else if(lookup === false)
{ // all other static files
// not a javascript file
try try
{ {
const type = MIME.typeByExtension(url.pathname.substring(url.pathname.lastIndexOf("."))) || "text/html"; const type = MIME.typeByExtension(ext);
const file = await fetch(Configure.Proxy + url.pathname); const file = await fetch(Configure.Proxy + url.pathname);
const text = await file.text(); const text = await file.text();
return new Response(text, {headers:{"content-type":type, "Access-Control-Allow-Origin":Configure.Allow, charset:"utf-8"}}); return new Response(text, {headers:{...headers, "content-type":type||""}});
} }
catch(e) catch(e)
{ {
return new Response(`404 ${Configure.Proxy + url.pathname}`, {status:404}); return new Response(`{"error":"${e}", "path":"${url.pathname}"}`, {status:404, headers});
}
}
else
{
return new Response(lookup, {headers:{"content-type":"application/javascript", "Access-Control-Allow-Origin": Configure.Allow, charset:"utf-8"}});
} }
}); });