From c758f66b271ac397c187ab75d1f0581dd89072c6 Mon Sep 17 00:00:00 2001 From: Seth Trowbridge Date: Wed, 7 Jun 2023 11:22:49 -0400 Subject: [PATCH] more configuration --- local.tsx | 98 ++++++++++++++++++++++++++++----------- serve.tsx | 136 +++++++++++++++++++++++++++++++----------------------- 2 files changed, 148 insertions(+), 86 deletions(-) diff --git a/local.tsx b/local.tsx index a6bf756..dbd2d56 100644 --- a/local.tsx +++ b/local.tsx @@ -1,32 +1,71 @@ -import * as HTTP from "https://deno.land/std@0.177.0/http/server.ts"; -import Setup, {Transpile} from "./serve.tsx"; - -const Directory = `file://${Deno.cwd().replaceAll("\\", "/")}`; -Transpile.Config.sourceMaps = "inline"; -Setup({Proxy:Directory}); +import Setup, {Transpile, Extension} from "./serve.tsx"; const SocketsLive:Set = new Set(); const SocketsSend =(inData:string)=>{ console.log(inData); for (const socket of SocketsLive){ socket.send(inData); } } -HTTP.serve((_req:Request)=> -{ - if(_req.headers.get("upgrade") == "websocket") +const Directory = `file://${Deno.cwd().replaceAll("\\", "/")}`; + +Setup({ + Proxy:Directory, + SWCOp: { - try + sourceMaps: "inline", + minify: false, + jsc: { - const { response, socket } = Deno.upgradeWebSocket(_req); - socket.onopen = () => SocketsLive.add(socket); - socket.onclose = () => SocketsLive.delete(socket); - socket.onmessage = (e) => {}; - socket.onerror = (e) => console.log("Socket errored:", e); - return response; + target:"es2022", + parser: + { + syntax: "typescript", + tsx: true, + } } - catch(e) + }, + async Serve(inReq, inURL, inExt) + { + if(inReq.headers.get("upgrade") == "websocket") { - return new Response(e); + try + { + const { response, socket } = Deno.upgradeWebSocket(inReq); + socket.onopen = () => SocketsLive.add(socket); + socket.onclose = () => SocketsLive.delete(socket); + socket.onmessage = (e) => {}; + socket.onerror = (e) => console.log("Socket errored:", e); + return response; + } + catch(e) + { + return new Response(e); + } } + + if(!inExt) + { + await fetch(Directory+"/deno.json"); + + return new Response( +` + + + + +
+ + + +`, {headers:{"content-type":"text/html"}}); + } + + return false; } - return new Response(`websockets only`); -}, { port: 4444 }); +}); let blocking = false; const filesChanged:Map = new Map(); @@ -40,15 +79,18 @@ for await (const event of Deno.watchFs(Deno.cwd())) { for await (const [path, action] of filesChanged) { - const key = path.substring(Deno.cwd().length).replaceAll("\\", "/"); - if(action != "remove") - { - const tsx = await Transpile.Fetch(Directory+key, key, true); - tsx && SocketsSend(key); - } - else + if(Transpile.Check(Extension(path))) { - Transpile.Cache.delete(key); + const key = path.substring(Deno.cwd().length).replaceAll("\\", "/"); + if(action != "remove") + { + const tsx = await Transpile.Fetch(Directory+key, key, true, true); + tsx && SocketsSend(key); + } + else + { + Transpile.Cache.delete(key); + } } } filesChanged.clear(); diff --git a/serve.tsx b/serve.tsx index 860e4c3..8c69e79 100644 --- a/serve.tsx +++ b/serve.tsx @@ -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 SWCW from "https://esm.sh/@swc/wasm-web@1.3.62"; -export type Configuration = {Proxy:string, Allow:string, Reset:string, Local:boolean}; -export type ConfigurationArgs = {Proxy?:string, Allow?:string, Reset?:string, Local?:boolean}; -export let Configure:Configuration = +type CustomHTTPHandler = (inReq:Request, inURL:URL, inExtension:string|false)=>false|Response|Promise +type Configuration = {Proxy:string, Allow:string, Reset:string, SWCOp:SWCW.Options, Serve:CustomHTTPHandler}; +type ConfigurationArgs = {Proxy?:string, Allow?:string, Reset?:string, SWCOp?:SWCW.Options, Serve?:CustomHTTPHandler}; +let Configure:Configuration = { Proxy: "", Allow: "*", Reset: "/clear-cache", - Local: false -}; - -export default (config:ConfigurationArgs)=> Configure = {...Configure, ...config}; -export const Transpile = { - Config: + Serve: ()=>false, + SWCOp: { sourceMaps: false, minify: true, @@ -35,9 +32,19 @@ export const Transpile = { { react: { runtime: "automatic" } } - }, - } as SWCW.Options, + } + } +}; +export default (config:ConfigurationArgs)=> Configure = {...Configure, ...config}; + +export const Transpile = +{ Cache: new Map() as Map, + Files: ["tsx", "jsx", "ts", "js", "mjs"], + Check(inExtension:string|false) + { + return inExtension ? this.Files.includes(inExtension) : false; + }, Clear() { const size = this.Cache.size; @@ -46,76 +53,89 @@ export const Transpile = { }, 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); + if(check && inCheckCache) { - const check = this.Cache.get(inPath); - if(check && inCheckCache) - { - return check; - } - else - { - try - { - const resp = await fetch(inPath); - const text = await resp.text(); - const {code} = await SWCW.transform(text, {...this.Config, filename:inKey}); - this.Cache.set(inKey, code); - return code; - } - catch(e) - { - console.log(`xpile.tsx error. Key:${inKey} Path:${inPath} Error:"${e}"`); - return null; - } - } + return check; } else { - return false; + try + { + const resp = await fetch(inPath); + const text = await resp.text(); + const {code} = await SWCW.transform(text, { ...Configure.SWCOp, filename:inKey}); + this.Cache.set(inKey, code); + return code; + } + catch(e) + { + //console.log(`Transpile.Fetch error. Key:"${inKey}" Path:"${inPath}" Error:"${e}"`); + return null; + } } } }; +export const Extension =(inPath:string)=> +{ + const posSlash = inPath.lastIndexOf("/"); + const posDot = inPath.lastIndexOf("."); + return posDot > posSlash ? inPath.substring(posDot+1).toLowerCase() : false; +}; + SWCW.default(); -console.log("starting server"); HTTP.serve(async(req: Request)=> { 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(` + + + + + + + +`, {headers:{...headers, "content-type":"text/html"}}); + } + + // cache-reset route if(url.pathname === Configure.Reset) { - return new Response(`cache cleared (${Transpile.Clear()} items)`); + return new Response(`{"cleared":${Transpile.Clear()}}`, {headers}); } - const lookup = await Transpile.Fetch(Configure.Proxy + url.pathname, url.pathname); - if(lookup === null) + // transpileable files + if(Transpile.Check(ext)) { - // error - return new Response(`transpile error (see console)`, {status:404, headers:{"content-type":"application/javascript", "Access-Control-Allow-Origin": Configure.Allow, charset:"utf-8"}}); + const lookup = await Transpile.Fetch(Configure.Proxy + url.pathname, url.pathname); + return new Response(lookup, {status:lookup?200:404, headers:{...headers, "content-type":"application/javascript"}} ); } - else if(lookup === false) + + // all other static files + try { - // not a javascript file - try - { - const type = MIME.typeByExtension(url.pathname.substring(url.pathname.lastIndexOf("."))) || "text/html"; - const file = await fetch(Configure.Proxy + url.pathname); - const text = await file.text(); - return new Response(text, {headers:{"content-type":type, "Access-Control-Allow-Origin":Configure.Allow, charset:"utf-8"}}); - } - catch(e) - { - return new Response(`404 ${Configure.Proxy + url.pathname}`, {status:404}); - } + const type = MIME.typeByExtension(ext); + const file = await fetch(Configure.Proxy + url.pathname); + const text = await file.text(); + return new Response(text, {headers:{...headers, "content-type":type||""}}); } - else + catch(e) { - return new Response(lookup, {headers:{"content-type":"application/javascript", "Access-Control-Allow-Origin": Configure.Allow, charset:"utf-8"}}); + return new Response(`{"error":"${e}", "path":"${url.pathname}"}`, {status:404, headers}); } + }); \ No newline at end of file