modes #23

Merged
SethTrowbridge merged 7 commits from modes into master 2023-04-29 21:30:28 -04:00
2 changed files with 306 additions and 280 deletions
Showing only changes of commit 8917d179ef - Show all commits

View File

@ -9,6 +9,6 @@
}, },
"tasks": { "tasks": {
"host": "deno run -A --unstable https://deno.land/std@0.181.0/http/file_server.ts", "host": "deno run -A --unstable https://deno.land/std@0.181.0/http/file_server.ts",
"dev": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock --config=deno.jsonc 'http://localhost:4507/server.tsx?reload=1'" "dev": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock --config=deno.jsonc 'http://localhost:4507/server.tsx'"
} }
} }

View File

@ -60,11 +60,15 @@ const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=>
const LibPath = "lib"; const LibPath = "lib";
type ImportMap = {imports?:Record<string, string>, importMap?:string};
let App, TwindInst;
let ImportObject:ImportMap = {}; async function Configure(inDevMode:boolean, inLibPath:string)
try
{ {
type ImportMap = {imports?:Record<string, string>, importMap?:string};
const output:{Imports?:ImportMap, App?:React.FunctionComponent, TwindInst?:Twind.Twind, Error?:string} = {};
let ImportObject:ImportMap = {};
try
{
const confDeno = await fetch(`${Path.Active}/deno.jsonc`); const confDeno = await fetch(`${Path.Active}/deno.jsonc`);
const confText = await confDeno.text(); const confText = await confDeno.text();
const confDenoParsed = JSONC(confText) as ImportMap; const confDenoParsed = JSONC(confText) as ImportMap;
@ -75,47 +79,54 @@ try
const confImports = await Deno.readTextFile(confDenoParsed.importMap); const confImports = await Deno.readTextFile(confDenoParsed.importMap);
try try
{ {
ImportObject = JSON.parse(confImports); output.Imports = JSON.parse(confImports);
} }
catch(e) catch(e)
{ {
console.log(`"importMap" "${confDenoParsed.importMap}" contains invalid JSON`); output.Error = `"importMap" "${confDenoParsed.importMap}" contains invalid JSON`;
return output;
} }
} }
catch(e) catch(e)
{ {
console.log(`"importMap" "${confDenoParsed.importMap}" cannot be found`); output.Error = `"importMap" "${confDenoParsed.importMap}" cannot be found`;
return output;
} }
} }
else if(confDenoParsed.imports) else if(confDenoParsed.imports)
{ {
ImportObject = {imports:confDenoParsed.imports}; output.Imports = {imports:confDenoParsed.imports};
} }
if(ImportObject.imports) if(output.Imports?.imports)
{ {
const importReact = ImportObject.imports["react"]; if(inDevMode)
{
const importReact = output.Imports.imports["react"];
if(importReact) if(importReact)
{ {
ImportObject.imports["react-original"] = importReact; output.Imports.imports["react-original"] = importReact;
ImportObject.imports["react"] = `/${LibPath}/react.tsx`; output.Imports.imports["react"] = `/${inLibPath}/react.tsx`;
} }
else else
{ {
console.log(`"imports" configuration does not alias "react"`); output.Error = `"imports" configuration does not alias "react"`;
return output;
}
} }
const importIso = ImportObject.imports["@eno/iso"]; const importIso = output.Imports.imports["@eno/iso"];
if(importIso) if(importIso)
{ {
ImportObject.imports["@eno/iso"] = `/${LibPath}/iso.tsx`; output.Imports.imports["@eno/iso"] = `/${inLibPath}/iso.tsx`;
} }
else else
{ {
output.Error = `"imports" configuration does not alias "@eno/iso"`;
return output;
} }
const importApp = ImportObject.imports["@eno/app"]; const importApp = output.Imports.imports["@eno/app"];
if(importApp) if(importApp)
{ {
let appImport let appImport
@ -125,16 +136,18 @@ try
} }
catch(e) catch(e)
{ {
console.log(`"@eno/app" entry-point (${importApp}) file not found`) output.Error = `"@eno/app" entry-point (${importApp}) file not found`;
return output;
} }
if(typeof appImport.default == "function" ) if(typeof appImport.default == "function" )
{ {
App = appImport.default; output.App = appImport.default;
} }
else else
{ {
console.log(`"@eno/app" entry-point (${importApp}) needs to export a default function to use as the app root.`) output.Error = `"@eno/app" entry-point (${importApp}) needs to export a default function to use as the app root.`;
return output;
} }
let twindConfig = Iso.CSS; let twindConfig = Iso.CSS;
@ -145,41 +158,53 @@ try
try try
{ {
// @ts-ignore // @ts-ignore
TwindInst = Twind.install(twindConfig); output.TwindInst = Twind.install(twindConfig);
} }
catch(e) catch(e)
{ {
console.log(`CSS configuration is malformed`); output.Error = `CSS configuration is malformed`;
return output;
} }
} }
else else
{ {
console.log(`"imports" configuration does not alias an entry-point file as "@eno/app"`); output.Error = `"imports" configuration does not alias an entry-point file as "@eno/app"`;
return output;
} }
Object.entries(ImportObject.imports).forEach(([key, value])=>{ Object.entries(output.Imports.imports).forEach(([key, value])=>{
if(value.startsWith("./") && ImportObject.imports) if(value.startsWith("./") && output.Imports?.imports)
{ {
ImportObject.imports[key] = value.substring(1); output.Imports.imports[key] = value.substring(1);
} }
}) })
} }
else else
{ {
console.log(`No "imports" found in configuration`); output.Error = `No "imports" found in configuration`;
return output;
} }
} }
catch(e) catch(e)
{ {
console.log(`error during configuration: ${e}`); output.Error = `error during configuration: ${e}`;
return output;
}
return output;
} }
const {Imports, App, TwindInst, Error} = await Configure(true, LibPath);
Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) => if(Error)
{ {
console.log(Error);
}
if(App && TwindInst)
{
Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) =>
{
const url:URL = new URL(_req.url); const url:URL = new URL(_req.url);
const pathParts = url.pathname.substring(1, url.pathname.endsWith("/") ? url.pathname.length-1 : url.pathname.length).split("/"); const pathParts = url.pathname.substring(1, url.pathname.endsWith("/") ? url.pathname.length-1 : url.pathname.length).split("/");
const pathLast = pathParts.at(-1); const pathLast = pathParts.at(-1);
@ -235,17 +260,17 @@ Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) =>
const members = []; const members = [];
for( const key in imp ) { members.push(key); } for( const key in imp ) { members.push(key); }
body = body =
` `
import {FileListen} from "/${LibPath}/hmr.tsx"; import {FileListen} from "/${LibPath}/hmr.tsx";
import * as Import from "${url.pathname}?reload=0"; import * as Import from "${url.pathname}?reload=0";
${ members.map(m=>`let proxy_${m} = Import.${m}; ${ members.map(m=>`let proxy_${m} = Import.${m};
export { proxy_${m} as ${m} }; export { proxy_${m} as ${m} };
`).join(" ") } `).join(" ") }
const reloadHandler = (updatedModule)=> const reloadHandler = (updatedModule)=>
{ {
${ members.map(m=>`proxy_${m} = updatedModule.${m};`).join("\n") } ${ members.map(m=>`proxy_${m} = updatedModule.${m};`).join("\n") }
}; };
FileListen("${url.pathname}", reloadHandler);`; FileListen("${url.pathname}", reloadHandler);`;
} }
else else
@ -291,14 +316,14 @@ FileListen("${url.pathname}", reloadHandler);`;
type = `text/html`; type = `text/html`;
body = body =
`<!doctype html> `<!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<title>${Iso.Meta.title}</title> <title>${Iso.Meta.title}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta charset="utf-8"/> <meta charset="utf-8"/>
<style data-twind>${results.css}</style> <style data-twind>${results.css}</style>
<script type="importmap">${JSON.stringify(ImportObject)}</script> <script type="importmap">${JSON.stringify(Imports)}</script>
</head> </head>
<body> <body>
<div id="app">${results.html}</div> <div id="app">${results.html}</div>
@ -313,7 +338,7 @@ FileListen("${url.pathname}", reloadHandler);`;
hydrate( H(Router.Provider, null, hmrWrap), document.querySelector("#app")); hydrate( H(Router.Provider, null, hmrWrap), document.querySelector("#app"));
</script> </script>
</body> </body>
</html>`; </html>`;
} }
return new Response(body, {headers:{"content-type":type as string, "Access-Control-Allow-Origin":"*", charset:"utf-8"}}); return new Response(body, {headers:{"content-type":type as string, "Access-Control-Allow-Origin":"*", charset:"utf-8"}});
@ -323,14 +348,14 @@ FileListen("${url.pathname}", reloadHandler);`;
console.log(error); console.log(error);
return new Response(error, {status:404}); return new Response(error, {status:404});
} }
}); });
const Sockets:Set<WebSocket> = new Set(); const Sockets:Set<WebSocket> = new Set();
const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } } const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } }
const FilesChanged:Map<string, string> = new Map(); const FilesChanged:Map<string, string> = new Map();
const ProcessFiles =debounce(async()=> const ProcessFiles =debounce(async()=>
{ {
console.log("Processing Files...", FilesChanged); console.log("Processing Files...", FilesChanged);
for await (const [path, action] of FilesChanged) for await (const [path, action] of FilesChanged)
{ {
@ -349,9 +374,9 @@ const ProcessFiles =debounce(async()=>
} }
} }
FilesChanged.clear(); FilesChanged.clear();
}, 1000); }, 1000);
for await (const event of Deno.watchFs(Deno.cwd())) for await (const event of Deno.watchFs(Deno.cwd()))
{ {
event.paths.forEach( path => event.paths.forEach( path =>
{ {
if(Transpileable(path)) if(Transpileable(path))
@ -363,4 +388,5 @@ for await (const event of Deno.watchFs(Deno.cwd()))
{ {
ProcessFiles(); ProcessFiles();
} }
}
} }