Compare commits
No commits in common. "f7f87f8f38112c091c2c44da69ae0cba4f51a8d7" and "8ab67be4d8adc60e0c9db55d803a309ac78b8867" have entirely different histories.
f7f87f8f38
...
8ab67be4d8
@ -1,3 +1,5 @@
|
||||
import TWPreTail from "https://esm.sh/v115/@twind/preset-tailwind@1.1.4/es2022/preset-tailwind.mjs";
|
||||
import TWPreAuto from "https://esm.sh/v115/@twind/preset-autoprefix@1.0.7/es2022/preset-autoprefix.mjs";
|
||||
import React from "react";
|
||||
import * as Iso from "@eno/iso";
|
||||
|
||||
@ -29,3 +31,8 @@ export default ()=>
|
||||
</Iso.Switch>
|
||||
</div>;
|
||||
};
|
||||
|
||||
export const CSS = {
|
||||
presets: [TWPreTail(), TWPreAuto()],
|
||||
hash:false
|
||||
};
|
||||
|
@ -9,6 +9,6 @@
|
||||
},
|
||||
"tasks": {
|
||||
"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'"
|
||||
"dev": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock --config=deno.json 'http://localhost:4507/server.tsx?reload=1'"
|
||||
}
|
||||
}
|
@ -1,13 +1,5 @@
|
||||
import TWPreTail from "https://esm.sh/v115/@twind/preset-tailwind@1.1.4/es2022/preset-tailwind.mjs";
|
||||
import TWPreAuto from "https://esm.sh/v115/@twind/preset-autoprefix@1.0.7/es2022/preset-autoprefix.mjs";
|
||||
import React from "react";
|
||||
|
||||
export const CSS = {
|
||||
presets: [TWPreTail(), TWPreAuto()],
|
||||
hash:false
|
||||
};
|
||||
|
||||
|
||||
type Meta = {title:string, description:string, keywords:string, image:string, canonical:string }
|
||||
type MetaKeys = keyof Meta;
|
||||
export const Meta:Meta = {
|
||||
|
353
server.tsx
353
server.tsx
@ -1,23 +1,22 @@
|
||||
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";
|
||||
import { parse as JSONC} from "https://deno.land/std@0.185.0/jsonc/mod.ts";
|
||||
import SSR from "https://esm.sh/v113/preact-render-to-string@6.0.2";
|
||||
import Prepass from "https://esm.sh/preact-ssr-prepass@1.2.0";
|
||||
import * as Twind from "https://esm.sh/@twind/core@1.1.3";
|
||||
import React from "react";
|
||||
import * as Iso from "@eno/iso";
|
||||
|
||||
/**
|
||||
* Setup a transpiler.
|
||||
* @param inDevMode When true, starts a file-watcher
|
||||
* @returns
|
||||
*/
|
||||
function Transpiler(inDevMode:boolean)
|
||||
let hosted = import.meta.resolve("./");
|
||||
const Path = {
|
||||
Hosted:hosted.substring(0, hosted.length-1),
|
||||
Active:`file://${Deno.cwd().replaceAll("\\", "/")}`
|
||||
};
|
||||
console.log(Path);
|
||||
|
||||
const Transpiled = new Map();
|
||||
const Transpileable =(inFilePath:string):boolean=>
|
||||
{
|
||||
const Transpiled = new Map();
|
||||
const Transpileable =(inFilePath:string):boolean=>
|
||||
{
|
||||
let dotIndex = inFilePath.length-4;
|
||||
if(inFilePath[dotIndex] !== ".")
|
||||
{
|
||||
@ -34,17 +33,17 @@ function Transpiler(inDevMode:boolean)
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
const Transpile =async(inCode:string, inKey:string):Promise<string>=>
|
||||
{
|
||||
const transpile = await ESBuild.transform(inCode, inDevMode ? { loader: "tsx", sourcemap:"inline", minify: false, sourcefile:inKey} : {loader:"tsx", minify: true});
|
||||
};
|
||||
const Transpile =async(inCode:string, inKey:string):Promise<string>=>
|
||||
{
|
||||
const transpile = await ESBuild.transform(inCode, { loader: "tsx", sourcemap:"inline", minify:true, sourcefile:inKey});
|
||||
|
||||
Transpiled.set(inKey, transpile.code);
|
||||
return transpile.code;
|
||||
};
|
||||
type Transpiler = (inPath:string, inKey:string, inCheck?:boolean)=>Promise<string>;
|
||||
const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=>
|
||||
{
|
||||
};
|
||||
type Transpiler = (inPath:string, inKey:string, inCheck?:boolean)=>Promise<string>;
|
||||
const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=>
|
||||
{
|
||||
if(inCheck)
|
||||
{
|
||||
const cached = Transpiled.get(inKey);
|
||||
@ -56,94 +55,16 @@ function Transpiler(inDevMode:boolean)
|
||||
let body = await fetch(inPath);
|
||||
let text = await body.text();
|
||||
return Transpile(text, inKey);
|
||||
};
|
||||
};
|
||||
|
||||
const Sockets:Set<WebSocket> = new Set();
|
||||
const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } }
|
||||
const SocketsHandler = inDevMode ? (_req:Request)=>
|
||||
{
|
||||
if(_req.headers.get("upgrade") == "websocket")
|
||||
{
|
||||
try
|
||||
{
|
||||
const { response, socket } = Deno.upgradeWebSocket(_req);
|
||||
socket.onopen = () => Sockets.add(socket);
|
||||
socket.onclose = () => Sockets.delete(socket);
|
||||
socket.onmessage = (e) => {};
|
||||
socket.onerror = (e) => console.log("Socket errored:", e);
|
||||
return response;
|
||||
}
|
||||
catch(e)
|
||||
{
|
||||
//
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
:
|
||||
()=>false;
|
||||
|
||||
const watcher =async()=>
|
||||
{
|
||||
const FilesChanged:Map<string, string> = new Map();
|
||||
const ProcessFiles =debounce(async()=>
|
||||
{
|
||||
for await (const [path, action] of FilesChanged)
|
||||
{
|
||||
const key = path.substring(Deno.cwd().length).replaceAll("\\", "/");
|
||||
if(action != "remove")
|
||||
{
|
||||
await TranspileURL(Path.Active+key, key, false);
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(inDevMode)
|
||||
{
|
||||
watcher().then(()=>{console.log("done watching");});
|
||||
}
|
||||
|
||||
return {TranspileURL, Transpileable, SocketsHandler};
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract all configuration info form a project's deno.jsonc file
|
||||
* @param inDevMode When true, proxies react to an HMR-enabled version
|
||||
* @param inLibPath
|
||||
* @returns
|
||||
*/
|
||||
async function Configure(inDevMode:boolean, inLibPath:string)
|
||||
const LibPath = "lib";
|
||||
type ImportMap = {imports?:Record<string, string>, importMap?:string};
|
||||
let ImportObject:ImportMap = {};
|
||||
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 confText = await confDeno.text();
|
||||
const confDenoParsed = JSONC(confText) as ImportMap;
|
||||
const confDeno = await fetch(`${Path.Active}/deno.json`);
|
||||
const confDenoParsed:ImportMap = await confDeno.json();
|
||||
if(confDenoParsed.importMap)
|
||||
{
|
||||
try
|
||||
@ -151,148 +72,108 @@ async function Configure(inDevMode:boolean, inLibPath:string)
|
||||
const confImports = await Deno.readTextFile(confDenoParsed.importMap);
|
||||
try
|
||||
{
|
||||
output.Imports = JSON.parse(confImports);
|
||||
ImportObject = JSON.parse(confImports);
|
||||
}
|
||||
catch(e)
|
||||
{
|
||||
output.Error = `"importMap" "${confDenoParsed.importMap}" contains invalid JSON`;
|
||||
return output;
|
||||
console.log(`"importMap" "${confDenoParsed.importMap}" contains invalid JSON`);
|
||||
}
|
||||
}
|
||||
catch(e)
|
||||
{
|
||||
output.Error = `"importMap" "${confDenoParsed.importMap}" cannot be found`;
|
||||
return output;
|
||||
console.log(`"importMap" "${confDenoParsed.importMap}" cannot be found`);
|
||||
}
|
||||
}
|
||||
else if(confDenoParsed.imports)
|
||||
{
|
||||
output.Imports = {imports:confDenoParsed.imports};
|
||||
ImportObject = {imports:confDenoParsed.imports};
|
||||
}
|
||||
|
||||
if(output.Imports?.imports)
|
||||
if(ImportObject.imports)
|
||||
{
|
||||
if(inDevMode)
|
||||
{
|
||||
const importReact = output.Imports.imports["react"];
|
||||
const importReact = ImportObject.imports["react"];
|
||||
if(importReact)
|
||||
{
|
||||
output.Imports.imports["react-original"] = importReact;
|
||||
output.Imports.imports["react"] = `/${inLibPath}/react.tsx`;
|
||||
ImportObject.imports["react-original"] = importReact;
|
||||
ImportObject.imports["react"] = `/${LibPath}/react.tsx`;
|
||||
}
|
||||
else
|
||||
{
|
||||
output.Error = `"imports" configuration does not alias "react"`;
|
||||
return output;
|
||||
}
|
||||
console.log(`"imports" configuration does not alias "react"`);
|
||||
}
|
||||
|
||||
const importIso = output.Imports.imports["@eno/iso"];
|
||||
if(importIso)
|
||||
{
|
||||
output.Imports.imports["@eno/iso"] = `/${inLibPath}/iso.tsx`;
|
||||
}
|
||||
else
|
||||
{
|
||||
output.Error = `"imports" configuration does not alias "@eno/iso"`;
|
||||
return output;
|
||||
}
|
||||
|
||||
const importApp = output.Imports.imports["@eno/app"];
|
||||
const importApp = ImportObject.imports["@eno/app"];
|
||||
if(importApp)
|
||||
{
|
||||
let appImport
|
||||
try
|
||||
{
|
||||
appImport = await import(Path.Active+importApp);
|
||||
}
|
||||
catch(e)
|
||||
{
|
||||
output.Error = `"@eno/app" entry-point (${importApp}) file not found`;
|
||||
return output;
|
||||
}
|
||||
|
||||
if(typeof appImport.default == "function" )
|
||||
{
|
||||
output.App = appImport.default;
|
||||
}
|
||||
else
|
||||
{
|
||||
output.Error = `"@eno/app" entry-point (${importApp}) needs to export a default function to use as the app root.`;
|
||||
return output;
|
||||
console.log(`"imports" configuration does not alias an entry-point component with "@eno/app"`);
|
||||
}
|
||||
|
||||
let twindConfig = Iso.CSS;
|
||||
if(typeof appImport.CSS == "object")
|
||||
const importIso = ImportObject.imports["@eno/iso"];
|
||||
if(importIso)
|
||||
{
|
||||
twindConfig = {...twindConfig, ...appImport.CSS};
|
||||
}
|
||||
try
|
||||
{
|
||||
// @ts-ignore
|
||||
output.TwindInst = Twind.install(twindConfig);
|
||||
}
|
||||
catch(e)
|
||||
{
|
||||
output.Error = `CSS configuration is malformed`;
|
||||
return output;
|
||||
}
|
||||
ImportObject.imports["@eno/iso"] = `/${LibPath}/iso.tsx`;
|
||||
}
|
||||
else
|
||||
{
|
||||
output.Error = `"imports" configuration does not alias an entry-point file as "@eno/app"`;
|
||||
return output;
|
||||
|
||||
}
|
||||
|
||||
|
||||
Object.entries(output.Imports.imports).forEach(([key, value])=>{
|
||||
if(value.startsWith("./") && output.Imports?.imports)
|
||||
Object.entries(ImportObject.imports).forEach(([key, value])=>{
|
||||
if(value.startsWith("./") && ImportObject.imports)
|
||||
{
|
||||
output.Imports.imports[key] = value.substring(1);
|
||||
ImportObject.imports[key] = value.substring(1);
|
||||
}
|
||||
})
|
||||
}
|
||||
else
|
||||
{
|
||||
output.Error = `No "imports" found in configuration`;
|
||||
return output;
|
||||
console.log(`No "imports" found in configuration`);
|
||||
}
|
||||
}
|
||||
catch(e)
|
||||
{
|
||||
output.Error = `error during configuration: ${e}`;
|
||||
return output;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
catch(e)
|
||||
{
|
||||
console.log(`deno.json not found`);
|
||||
}
|
||||
|
||||
let DevMode = true;
|
||||
let hosted = import.meta.resolve("./");
|
||||
const Path = {
|
||||
Hosted: hosted.substring(0, hosted.length-1),
|
||||
Active: `file://${Deno.cwd().replaceAll("\\", "/")}`,
|
||||
LibDir: "lib"
|
||||
};
|
||||
console.log(Path);
|
||||
console.log(`Dev Mode: ${DevMode}`);
|
||||
|
||||
const {Transpileable, TranspileURL, SocketsHandler} = Transpiler(DevMode);
|
||||
const {Imports, App, TwindInst, Error} = await Configure(DevMode, Path.LibDir);
|
||||
if(Error)
|
||||
Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) =>
|
||||
{
|
||||
console.log(Error);
|
||||
}
|
||||
else if(App && TwindInst)
|
||||
{
|
||||
Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) =>
|
||||
{
|
||||
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 pathLast = pathParts.at(-1);
|
||||
const pathExt:string|undefined = pathLast?.split(".")[1];
|
||||
|
||||
const resp = SocketsHandler(_req);
|
||||
if(resp){ return resp; }
|
||||
console.log(pathParts, pathLast, pathExt);
|
||||
|
||||
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
|
||||
{
|
||||
@ -300,7 +181,7 @@ else if(App && TwindInst)
|
||||
let type = `text/html`;
|
||||
let body:BodyInit = ``;
|
||||
|
||||
const isLib = url.pathname.startsWith(`/${Path.LibDir}/`);
|
||||
const isLib = url.pathname.startsWith(`/${LibPath}/`);
|
||||
|
||||
if(Transpileable(url.pathname))
|
||||
{
|
||||
@ -315,17 +196,17 @@ else if(App && TwindInst)
|
||||
const members = [];
|
||||
for( const key in imp ) { members.push(key); }
|
||||
body =
|
||||
`
|
||||
import {FileListen} from "/${Path.LibDir}/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)=>
|
||||
{
|
||||
`
|
||||
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);`;
|
||||
};
|
||||
FileListen("${url.pathname}", reloadHandler);`;
|
||||
|
||||
}
|
||||
else
|
||||
@ -337,7 +218,7 @@ else if(App && TwindInst)
|
||||
else if( pathExt )
|
||||
{
|
||||
type = MIME.typeByExtension(pathExt) || "text/html";
|
||||
const _fetch = await fetch((Path.Active)+url.pathname);
|
||||
const _fetch = await fetch((isLib ? Path.Hosted : Path.Active)+url.pathname);
|
||||
body = await _fetch.text();
|
||||
}
|
||||
else
|
||||
@ -371,29 +252,29 @@ else if(App && TwindInst)
|
||||
|
||||
type = `text/html`;
|
||||
body =
|
||||
`<!doctype html>
|
||||
<html lang="en">
|
||||
`<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<title>${Iso.Meta.title}</title>
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<meta charset="utf-8"/>
|
||||
<style data-twind>${results.css}</style>
|
||||
<script type="importmap">${JSON.stringify(Imports)}</script>
|
||||
<script type="importmap">${JSON.stringify(ImportObject)}</script>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app">${results.html}</div>
|
||||
<script type="module">
|
||||
import {hydrate, createElement as H} from "react";
|
||||
import * as Twind from "https://esm.sh/v115/@twind/core@1.1.3/es2022/core.mjs";
|
||||
import * as App from "@eno/app";
|
||||
import {Router, Fetch, CSS} from "@eno/iso";
|
||||
Twind.install(App.CSS ? {...CSS, ...App.CSS} : CSS);
|
||||
import {default as App, CSS} from "@eno/app";
|
||||
import {Router, Fetch} from "@eno/iso";
|
||||
Twind.install(CSS);
|
||||
Fetch.Seed(${JSON.stringify(seed)});
|
||||
const hmrWrap = H( ()=>H(App.default) );
|
||||
const hmrWrap = H( ()=>H(App) );
|
||||
hydrate( H(Router.Provider, null, hmrWrap), document.querySelector("#app"));
|
||||
</script>
|
||||
</body>
|
||||
</html>`;
|
||||
</html>`;
|
||||
}
|
||||
|
||||
return new Response(body, {headers:{"content-type":type as string, "Access-Control-Allow-Origin":"*", charset:"utf-8"}});
|
||||
@ -403,5 +284,47 @@ else if(App && TwindInst)
|
||||
console.log(error);
|
||||
return new Response(error, {status:404});
|
||||
}
|
||||
});
|
||||
|
||||
import App, {CSS} from "@eno/app";
|
||||
const TwindInst = Twind.install(CSS);
|
||||
|
||||
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 TranspileURL(Path.Active+key, 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();
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user