Compare commits

..

No commits in common. "master" and "misc" have entirely different histories.
master ... misc

10 changed files with 385 additions and 573 deletions

3
.vscode/launch.json vendored
View File

@ -10,9 +10,10 @@
"type": "node", "type": "node",
"program": "${workspaceFolder}/server.tsx", "program": "${workspaceFolder}/server.tsx",
"cwd": "${workspaceFolder}", "cwd": "${workspaceFolder}",
"runtimeExecutable": "deno.exe", "runtimeExecutable": "C:\\Users\\Seth\\.deno\\bin\\deno.EXE",
"runtimeArgs": [ "runtimeArgs": [
"run", "run",
"--no-lock",
"--unstable", "--unstable",
"--inspect-wait", "--inspect-wait",
"--allow-all" "--allow-all"

View File

@ -1,52 +1,16 @@
{ {
"version": "2", "version": "2",
"remote": { "remote": {
"https://deno.land/std@0.151.0/async/debounce.ts": "564273ef242bcfcda19a439132f940db8694173abffc159ea34f07d18fc42620", "http://localhost:4507/lib/iso.tsx": "edf1cf4c539900040c75824eac8472e0ec43098b13af4049bd79ddbd76a5346d",
"https://deno.land/std@0.180.0/media_types/_db.ts": "7606d83e31f23ce1a7968cbaee852810c2cf477903a095696cdc62eaab7ce570",
"https://deno.land/std@0.180.0/media_types/_util.ts": "916efbd30b6148a716f110e67a4db29d6949bf4048997b754415dd7e42c52378",
"https://deno.land/std@0.180.0/media_types/content_type.ts": "c682589a0aeb016bfed355cc1ed6fbb3ead2ea48fc0000ac5de6a5730613ad1c",
"https://deno.land/std@0.180.0/media_types/extension.ts": "7a4ef2813d7182f724a941f38161525996e4a67abc3cf6a0f9bc2168d73a0f0e",
"https://deno.land/std@0.180.0/media_types/extensions_by_type.ts": "4358023feac696e6e9d49c0f1e76a859f03ca254df57812f31f8536890c3a443",
"https://deno.land/std@0.180.0/media_types/format_media_type.ts": "1e35e16562e5c417401ffc388a9f8f421f97f0ee06259cbe990c51bae4e6c7a8",
"https://deno.land/std@0.180.0/media_types/get_charset.ts": "8be15a1fd31a545736b91ace56d0e4c66ea0d7b3fdc5c90760e8202e7b4b1fad",
"https://deno.land/std@0.180.0/media_types/mod.ts": "d3f0b99f85053bc0b98ecc24eaa3546dfa09b856dc0bbaf60d8956d2cdd710c8",
"https://deno.land/std@0.180.0/media_types/parse_media_type.ts": "bed260d868ea271445ae41d748e7afed9b5a7f407d2777ead08cecf73e9278de",
"https://deno.land/std@0.180.0/media_types/type_by_extension.ts": "6076a7fc63181d70f92ec582fdea2c927eb2cfc7f9c9bee9d6add2aca86f2355",
"https://deno.land/std@0.180.0/media_types/vendor/mime-db.v1.52.0.ts": "6925bbcae81ca37241e3f55908d0505724358cda3384eaea707773b2c7e99586",
"https://deno.land/std@0.185.0/_util/asserts.ts": "178dfc49a464aee693a7e285567b3d0b555dc805ff490505a8aae34f9cfb1462",
"https://deno.land/std@0.185.0/json/common.ts": "ecd5e87d45b5f0df33238ed8b1746e1444da7f5c86ae53d0f0b04280f41a25bb",
"https://deno.land/std@0.185.0/jsonc/mod.ts": "b88dce28eb3645667caa856538ae2fe87af51410822544a0b45a4177ef3bd7dd",
"https://deno.land/std@0.185.0/jsonc/parse.ts": "2910e33bc7c3b243e3b6f3a39ce4d6ca84337b277a8df6f2ad2d9e4adbcddc08",
"https://deno.land/x/denoflate@1.2.1/mod.ts": "f5628e44b80b3d80ed525afa2ba0f12408e3849db817d47a883b801f9ce69dd6",
"https://deno.land/x/denoflate@1.2.1/pkg/denoflate.js": "b9f9ad9457d3f12f28b1fb35c555f57443427f74decb403113d67364e4f2caf4",
"https://deno.land/x/denoflate@1.2.1/pkg/denoflate_bg.wasm.js": "d581956245407a2115a3d7e8d85a9641c032940a8e810acbd59ca86afd34d44d",
"https://deno.land/x/esbuild@v0.17.4/mod.d.ts": "dc279a3a46f084484453e617c0cabcd5b8bd1920c0e562e4ea02dfc828c8f968",
"https://deno.land/x/esbuild@v0.17.4/mod.js": "28f92694d79c8ef313e7ead7bb0e915551a805c3ad14dd2af24bbb0872e38c0d",
"https://esm.sh/@twind/core@1.1.3": "022193fe0f683445f35b232bf4a105d2c2aa48cc035332b4939d4f795c7ed48f",
"https://esm.sh/preact-ssr-prepass@1.2.0": "2ad461cd2ebd0ccb3b0345102e51f94923084f089b85805da5ca97d0b8db77d2",
"https://esm.sh/preact@10.13.2/compat": "1cf68e0c8c6c84b60d42f30665403b67229c16ff5206824709b19df60ba9cdc3", "https://esm.sh/preact@10.13.2/compat": "1cf68e0c8c6c84b60d42f30665403b67229c16ff5206824709b19df60ba9cdc3",
"https://esm.sh/stable/preact@10.13.2/deno/compat.js": "3151a948abd84aa75dfc9e57733da7e1a45fff7a25de58c7b6025b923874b508", "https://esm.sh/stable/preact@10.13.2/deno/compat.js": "3151a948abd84aa75dfc9e57733da7e1a45fff7a25de58c7b6025b923874b508",
"https://esm.sh/stable/preact@10.13.2/deno/hooks.js": "c7a8e703bcbc6a05949f329b618c33d5d1ea5fee113ddcea44ff0f527af8556f", "https://esm.sh/stable/preact@10.13.2/deno/hooks.js": "c7a8e703bcbc6a05949f329b618c33d5d1ea5fee113ddcea44ff0f527af8556f",
"https://esm.sh/stable/preact@10.13.2/deno/preact.mjs": "365fab897381f4f403f859c5d12939084560545567108cc90dae901bbe892578", "https://esm.sh/stable/preact@10.13.2/deno/preact.mjs": "365fab897381f4f403f859c5d12939084560545567108cc90dae901bbe892578",
"https://esm.sh/v113/preact-render-to-string@6.0.2": "9e27e8724b3e53ba3d006146efa7ac0d6764672e4cd7a2fb5738412526c2b16d", "https://esm.sh/v116/preact@10.13.2/compat/src/index.d.ts": "d02f015638a40e32649151e011cfda7b520d66f7fbd3c12a28fa03de2a5e1421",
"https://esm.sh/v113/preact-render-to-string@6.0.2/deno/preact-render-to-string.mjs": "09ead691b3745189a4171a6ee0948592c7a862b1bf1a97fe651fb34f88eabe3b", "https://esm.sh/v116/preact@10.13.2/compat/src/suspense-list.d.ts": "b8e274324392157ce476ef3a48ae215c9f7003b08525d140645f19eab20d1948",
"https://esm.sh/v113/preact-render-to-string@6.0.2/src/index.d.ts": "3df00ff7e5f6dc9d2d6b944a88c2e541b098c0e559bd3a918732f3aa35acf1af", "https://esm.sh/v116/preact@10.13.2/compat/src/suspense.d.ts": "81f5266e0977a94347505d11b8103024211f2b4f3b2eb2aa276a10d8fd169e65",
"https://esm.sh/v113/preact@10.13.2/src/index.d.ts": "65398710de6aa0a07412da79784e05e6e96763f51c7c91b77344d2d0af06385c", "https://esm.sh/v116/preact@10.13.2/hooks/src/index.d.ts": "5c29febb624fc25d71cb0e125848c9b711e233337a08f7eacfade38fd4c14cc3",
"https://esm.sh/v113/preact@10.13.2/src/jsx.d.ts": "9ac9b82c199fa7b04748807d750eba1a106c0be52041b8617416f88d6fc0a257", "https://esm.sh/v116/preact@10.13.2/src/index.d.ts": "65398710de6aa0a07412da79784e05e6e96763f51c7c91b77344d2d0af06385c",
"https://esm.sh/v115/@twind/core@1.1.3/es2022/core.mjs": "937e906c390266871215f71372af7fadf98274fb47670a7e1e8cf98e775357a8", "https://esm.sh/v116/preact@10.13.2/src/jsx.d.ts": "9ac9b82c199fa7b04748807d750eba1a106c0be52041b8617416f88d6fc0a257"
"https://esm.sh/v115/@twind/preset-autoprefix@1.0.7/es2022/preset-autoprefix.mjs": "082486172119c516f5daf83cd178175302455fab8ed550a3cb58630864f0c4e3",
"https://esm.sh/v115/@twind/preset-tailwind@1.1.4/es2022/preset-tailwind.mjs": "7c561cfa2c639b259c390d4412f88b2f0675431b995261f1a5ef0916f1b9b48b",
"https://esm.sh/v115/style-vendorizer@2.2.3/es2022/style-vendorizer.mjs": "b0f813226f7c4a30e1742087311243bbb021ef9b201e064932fce1122625b29e",
"https://esm.sh/v118/preact-ssr-prepass@1.2.0/deno/preact-ssr-prepass.mjs": "302a0da48c6fb2232c6f713f17957e409ec909ccb8f5a4074065eb0ca7553ee3",
"https://esm.sh/v118/preact-ssr-prepass@1.2.0/typings/index.d.ts": "68d54a22a76ef21fd95266ba4d8c71b3228d5e7769baf899998d5348018671c4",
"https://esm.sh/v118/preact@10.13.2/compat/src/index.d.ts": "d02f015638a40e32649151e011cfda7b520d66f7fbd3c12a28fa03de2a5e1421",
"https://esm.sh/v118/preact@10.13.2/compat/src/suspense-list.d.ts": "b8e274324392157ce476ef3a48ae215c9f7003b08525d140645f19eab20d1948",
"https://esm.sh/v118/preact@10.13.2/compat/src/suspense.d.ts": "81f5266e0977a94347505d11b8103024211f2b4f3b2eb2aa276a10d8fd169e65",
"https://esm.sh/v118/preact@10.13.2/hooks/src/index.d.ts": "5c29febb624fc25d71cb0e125848c9b711e233337a08f7eacfade38fd4c14cc3",
"https://esm.sh/v118/preact@10.13.2/src/index.d.ts": "65398710de6aa0a07412da79784e05e6e96763f51c7c91b77344d2d0af06385c",
"https://esm.sh/v118/preact@10.13.2/src/jsx.d.ts": "9ac9b82c199fa7b04748807d750eba1a106c0be52041b8617416f88d6fc0a257",
"https://esm.sh/v119/@twind/core@1.1.3/core.d.ts": "87836d90ff43c5bd5cbb53df7adbcad9d9515fae21f8a31d34203027b7d75d29",
"https://esm.sh/v119/@twind/core@1.1.3/deno/core.mjs": "9a65476bdc46aeb10894c4496fbfbc863e45ffebf43e58d6320017f847aca7b2",
"https://esm.sh/v119/csstype@3.1.2/index.d.ts": "4c68749a564a6facdf675416d75789ee5a557afda8960e0803cf6711fa569288"
} }
} }

View File

@ -1,33 +1,14 @@
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 React from "react";
import * as Iso from "@eno/iso"; import * as Iso from "@eno/iso";
/*
const delay =(inMS:number)=>
{
return new Promise((accept)=>
{
setTimeout(()=>
{
accept({default:()=>
{
return <h1>loooooool</h1>;
}});
}, inMS);
});
}
const LOL = React.lazy(()=>delay(3000));
*/
const Comp = React.lazy(()=>import("./deep/component.tsx")); const Comp = React.lazy(()=>import("./deep/component.tsx"));
export default ()=> export default ()=>
{ {
const [stack] = React.useContext(Iso.Meta.Context);
return <div class="p-4 font-sans"> return <div class="p-4 font-sans">
<Iso.Meta.Metas title="Main Page!" description="its great"/> <Iso.Meta.Metas title="Main Page!"/>
<nav class="p-4"> <nav class="p-4">
<a class="text-red-500" href="/">Home</a> <a class="text-red-500" href="/">Home</a>
<a href="/about">About</a> <a href="/about">About</a>
@ -39,15 +20,11 @@ export default ()=>
<Comp/> <Comp/>
</React.Suspense> </React.Suspense>
<Iso.Switch> <Iso.Switch>
<Iso.Case value="/">
<p>thing1</p>
<p>thing2</p>
</Iso.Case>
<Iso.Case value="page"> <Iso.Case value="page">
<Iso.Switch> <Iso.Switch>
<Iso.Case value="about-us"> <Iso.Case value="about-us">
<> <>
<Iso.Meta.Metas title="About US" concatListed=" | "/> <Iso.Meta.Metas title="About US"/>
About us! About us!
</> </>
</Iso.Case> </Iso.Case>
@ -55,12 +32,12 @@ export default ()=>
</Iso.Switch> </Iso.Switch>
</Iso.Case> </Iso.Case>
<Iso.Case value="lol/idk">lol/idk</Iso.Case> <Iso.Case value="lol/idk">lol/idk</Iso.Case>
<Iso.Case default> <Iso.Case default><p>404!</p></Iso.Case>
<>
<Iso.Meta.Metas description="a 404 has occurred"/>
<p>404!</p>
</>
</Iso.Case>
</Iso.Switch> </Iso.Switch>
</div>; </div>;
}; };
export const CSS = {
presets: [TWPreTail(), TWPreAuto()],
hash:false
};

View File

@ -13,7 +13,7 @@ export default ()=>
console.log("component.tsx render!!") console.log("component.tsx render!!")
return <div class="p-4 text-red-500"> return <div class="p-4 text-red-500">
<Iso.Meta.Metas title="Component!" description="components can set metas"/> <Iso.Meta.Metas title="Component!"/>
Component Route is: {routeGet.Path.toString()} Component Route is: {routeGet.Path.toString()}
<button className="p-4 bg-green-500 text-white" onClick={e=>{countSet(countGet+1); routeSet(["lol", "idk"], {count:countGet+1});}}>{countGet}</button> <button className="p-4 bg-green-500 text-white" onClick={e=>{countSet(countGet+1); routeSet(["lol", "idk"], {count:countGet+1});}}>{countGet}</button>
<a href="/page/about-us" className="p-2 text(lg blue-500) font-bold">a link</a> <a href="/page/about-us" className="p-2 text(lg blue-500) font-bold">a link</a>

View File

@ -2,12 +2,13 @@
"compilerOptions": {"lib": ["deno.window", "dom"]}, "compilerOptions": {"lib": ["deno.window", "dom"]},
"imports": "imports":
{ {
"react": "https://esm.sh/stable/preact@10.13.2/compat", "react": "https://esm.sh/preact@10.13.2/compat",
"@deep/": "./deep/",
"@eno/app": "./app.tsx", "@eno/app": "./app.tsx",
"@eno/iso": "http://localhost:4507/lib/iso.tsx" "@eno/iso": "http://localhost:4507/lib/iso.tsx"
}, },
"tasks": { "tasks": {
"dev": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock app.tsx --dev", "host": "deno run -A --unstable https://deno.land/std@0.181.0/http/file_server.ts",
"run": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock app.tsx" "dev": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock --config=deno.json 'http://localhost:4507/server.tsx?reload=1'"
} }
} }

35
fetch.test.tsx Normal file
View File

@ -0,0 +1,35 @@
import {Fetch} from "./lib/iso.tsx";
const delay =async(inHandler:()=>void, inDelay:number):Promise<void>=>
{
return new Promise((accept)=>{
setTimeout(()=>{
accept(inHandler());
}, inDelay);
});
};
const queue = [1, 2, 3];
while(queue.length)
{
await(delay(()=>{console.log(queue.pop())}, 1000))
}
console.log("all done!");
/*
let r1, r2, r3;
delay(()=>{r1 = Fetch.Request(`https://catfact.ninja/fact`, undefined, 0.2); console.log(r1); }, 10);
delay(()=>{r2 = Fetch.Request(`https://catfact.ninja/fact`, undefined, 0.2); console.log(r2); }, 20);
delay(()=>{r3 = Fetch.Request(`https://catfact.ninja/fact`, undefined, 0.2); console.log(r3); }, 2000);
await delay(()=>{}, 3000);
console.log(r1);
console.log(r2);
console.log(r3);
*/

View File

@ -1,8 +1,7 @@
let reloads = 0; let reloads = 0;
const listeners = new Map() as Map<string, Array<(module:unknown)=>void>>; const listeners = new Map() as Map<string, Array<(module:unknown)=>void>>;
const socket:WebSocket = new WebSocket("ws://"+document.location.host); new WebSocket("ws://"+document.location.host).addEventListener('message', (event) =>
socket.addEventListener('message', (event) =>
{ {
let handlers = listeners.get(event.data)??[]; let handlers = listeners.get(event.data)??[];
reloads++; reloads++;
@ -14,7 +13,6 @@ socket.addEventListener('message', (event) =>
}) })
).then(()=>HMR.update()); ).then(()=>HMR.update());
}); });
const socketTimer = setInterval(()=>{socket.send("ping")}, 1000);
export const FileListen =(inPath:string, inHandler:()=>void)=> export const FileListen =(inPath:string, inHandler:()=>void)=>
{ {

View File

@ -1,26 +1,14 @@
import TWPreTail from "https://esm.sh/v115/@twind/preset-tailwind@1.1.4/es2022/preset-tailwind.mjs"; import React from "react";
import TWPreAuto from "https://esm.sh/v115/@twind/preset-autoprefix@1.0.7/es2022/preset-autoprefix.mjs";
import React, { JSX } from "react";
export const CSS = {
presets: [TWPreTail(), TWPreAuto()],
hash:false
};
if(!window.innerWidth && !Deno.mainModule.endsWith("server.tsx"))
{
import(import.meta.resolve("../../server.tsx")).then(()=>{console.log("...imported!");});
}
type MetasInputs = { [Property in MetaKeys]?: string }; type MetasInputs = { [Property in MetaKeys]?: string };
type MetasModeArgs = {concatListed?:string; dropUnlisted?:boolean}; type MetasModeArgs = {concatListed?:boolean; dropUnlisted?:boolean};
type MetasStackItem = MetasModeArgs&MetasInputs&{id:string, depth:number} type MetasStackItem = MetasModeArgs&MetasInputs&{id:string, depth:number}
type Meta = {title:string, description:string, keywords:string, image:string, canonical:string } type Meta = {title:string, description:string, keywords:string, image:string, canonical:string }
type MetaKeys = keyof Meta; type MetaKeys = keyof Meta;
export const Meta = export const Meta =
{ {
Stack:[] as MetasStackItem[], Stack:[] as Array<MetasStackItem>,
Meta: { Meta: {
title:"", title:"",
description:"", description:"",
@ -28,83 +16,20 @@ export const Meta =
image:"", image:"",
canonical:"" canonical:""
} as Meta, } as Meta,
ComputeFinal(inStack:MetasStackItem[], inStart=0)
{
const seed = {
title:"",
description:"",
keywords:"",
image:"",
canonical:""
};
if(inStack.length>0)
{
let final = {...seed, ...inStack[0]};
for(let i=inStart+1; i<inStack.length; i++)
{
const curr = inStack[i];
Object.keys(seed).forEach(key=>
{
const lookup = key as MetaKeys
const valPrev = final[lookup];
const valCurr = curr[lookup];
if(valPrev && !valCurr)
{
final[lookup] = curr.dropUnlisted ? "" : valPrev;
}
else if(valPrev && valCurr)
{
final[lookup] = curr.concatListed ? valPrev + curr.concatListed + valCurr : valCurr
}
else
{
final[lookup] = valCurr||"";
}
});
}
return final;
}
else
{
return seed;
}
},
Context: React.createContext([[], ()=>{}] as [Get:MetasStackItem[], Set:React.StateUpdater<MetasStackItem[]>]), Context: React.createContext([[], ()=>{}] as [Get:MetasStackItem[], Set:React.StateUpdater<MetasStackItem[]>]),
Provider({children}:{children:Children}) Provider({children}:{children:Children})
{ {
const binding = React.useState([] as MetasStackItem[]); const binding = React.useState([] as MetasStackItem[]);
type MetaDOM = {description:NodeListOf<Element>, title:NodeListOf<Element>, image:NodeListOf<Element>, url:NodeListOf<Element>}; React.useEffect(()=>{
const stack = binding[0];
const refElements = React.useRef(null as null | MetaDOM); const last = stack[stack.length-1];
console.log("updating page title", stack);
React.useEffect(()=> document.title = last?.title||"";
{ })
refElements.current = {
description:document.querySelectorAll(`head > meta[name$='description']`),
title:document.querySelectorAll(`head > meta[name$='title']`),
image:document.querySelectorAll(`head > meta[name$='image']`),
url:document.querySelectorAll(`head > link[rel='canonical']`)
};
}, []);
React.useEffect(()=>
{
if(refElements.current)
{
const final = Meta.ComputeFinal(binding[0]);
refElements.current.url.forEach(e=>e.setAttribute("content", final.canonical||""));
document.title = final.title;
refElements.current.title.forEach(e=>e.setAttribute("content", final.title||""));
refElements.current.image.forEach(e=>e.setAttribute("content", final.image||""));
refElements.current.description.forEach(e=>e.setAttribute("content", final.description||""));
}
});
return <Meta.Context.Provider value={binding}>{children}</Meta.Context.Provider>; return <Meta.Context.Provider value={binding}>{children}</Meta.Context.Provider>;
}, },
Metas({concatListed=undefined, dropUnlisted=false, ...props}:MetasModeArgs&MetasInputs):null Metas({concatListed=false, dropUnlisted=false, ...props}:MetasModeArgs&MetasInputs):null
{ {
const id = React.useId(); const id = React.useId();
const [, metasSet] = React.useContext(Meta.Context); const [, metasSet] = React.useContext(Meta.Context);
@ -119,6 +44,7 @@ export const Meta =
{ {
if(clone[i].depth <= depth) if(clone[i].depth <= depth)
{ {
break; break;
} }
} }
@ -154,11 +80,34 @@ export const Meta =
}); });
}, Object.keys(props).map( (key) => props[key as MetaKeys] )); }, Object.keys(props).map( (key) => props[key as MetaKeys] ));
if(!window.innerWidth && props.title) /*
React.useEffect(()=>{
metasSet((m)=>
{ {
Meta.Stack.push({id, depth, concatListed, dropUnlisted, ...props}); const metas = {...m};
const additive = concatListed ? (key:MetaKeys, value:string)=> metas[key] += value : (key:MetaKeys, value:string)=> metas[key] = value;
const subtractive = dropUnlisted ? (key:MetaKeys)=> metas[key] = "" : (key:MetaKeys)=> {};
Object.keys(metas).forEach((key)=>{
const metaKey = key as MetaKeys;
const propValue = props[metaKey]||"";
propValue ? additive(metaKey, propValue) : subtractive(metaKey);
});
Meta.Meta = metas;
console.log(Meta.Meta);
if(window.innerWidth)
{
document.title = metas.title;
} }
return metas;
});
}, [props]);
*/
return null; return null;
} }
}; };
@ -280,7 +229,7 @@ export const Switch =({children}:{children:Children})=>
for(let i=0; i<children.length; i++) for(let i=0; i<children.length; i++)
{ {
const childCase = children[i]; const childCase = children[i];
const childCaseChildren = childCase.props?.__args?.slice(2) || childCase.props.children; const childCaseChildren = childCase.props?.__args?.[2] || childCase.props.children;
const newContextValue = checkChild(childCase); const newContextValue = checkChild(childCase);
if(newContextValue) if(newContextValue)
{ {

View File

@ -1,25 +1,22 @@
import * as ESBuild from 'https://deno.land/x/esbuild@v0.17.4/mod.js'; 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 * 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 { 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 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 Prepass from "https://esm.sh/preact-ssr-prepass@1.2.0";
import * as Twind from "https://esm.sh/@twind/core@1.1.3"; import * as Twind from "https://esm.sh/@twind/core@1.1.3";
import React from "react"; import React from "react";
import * as Iso from "@eno/iso"; import * as Iso from "@eno/iso";
Deno.env.set("initialized", "true"); 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();
* Setup a transpiler. const Transpileable =(inFilePath:string):boolean=>
* @param inDevMode When true, starts a file-watcher
* @returns
*/
function Transpiler(inDevMode:boolean)
{ {
const Transpiled = new Map();
const Transpileable =(inFilePath:string):boolean=>
{
let dotIndex = inFilePath.length-4; let dotIndex = inFilePath.length-4;
if(inFilePath[dotIndex] !== ".") if(inFilePath[dotIndex] !== ".")
{ {
@ -36,21 +33,17 @@ function Transpiler(inDevMode:boolean)
} }
return false; return false;
}; };
const Transpile =async(inCode:string, inKey:string):Promise<string>=> const Transpile =async(inCode:string, inKey:string):Promise<string>=>
{ {
const transpile = await ESBuild.transform(inCode, inDevMode ? { loader: "tsx", sourcemap:"inline", minify: false, sourcefile:inKey} : const transpile = await ESBuild.transform(inCode, { loader: "tsx", sourcemap:"inline", minify:true, sourcefile:inKey});
{ loader: "tsx",
minify:true,
jsx:"automatic",
jsxImportSource:"https://esm.sh/preact@10.13.2"});
Transpiled.set(inKey, transpile.code); Transpiled.set(inKey, transpile.code);
return transpile.code; return transpile.code;
}; };
type Transpiler = (inPath:string, inKey:string, inCheck?:boolean)=>Promise<string>; type Transpiler = (inPath:string, inKey:string, inCheck?:boolean)=>Promise<string>;
const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=> const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=>
{ {
if(inCheck) if(inCheck)
{ {
const cached = Transpiled.get(inKey); const cached = Transpiled.get(inKey);
@ -62,102 +55,16 @@ function Transpiler(inDevMode:boolean)
let body = await fetch(inPath); let body = await fetch(inPath);
let text = await body.text(); let text = await body.text();
return Transpile(text, inKey); 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;
let reloads = 0; const LibPath = "lib";
const watcher =async()=> type ImportMap = {imports?:Record<string, string>, importMap?:string};
{ let ImportObject:ImportMap = {};
const FilesChanged:Map<string, string> = new Map(); try
const ProcessFiles =debounce(async()=>
{
for await (const [path, action] of FilesChanged)
{
const key = path.substring(Deno.cwd().length).replaceAll("\\", "/");
if(action != "remove")
{
if(Imports?.imports)
{
reloads++;
const importApp = Imports.imports["@eno/app"];
const imp = await import(Path.Active+importApp+"?reloads="+reloads);
App = imp.default;
}
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)
{ {
type ImportMap = {imports?:Record<string, string>, importMap?:string}; const confDeno = await fetch(`${Path.Active}/deno.json`);
const output:{Imports?:ImportMap, App?:React.FunctionComponent, TwindInst?:Twind.Twind, Error?:string} = {}; const confDenoParsed:ImportMap = await confDeno.json();
let ImportObject:ImportMap = {};
try
{
const confDeno = await fetch(`${Path.Active}/deno.jsonc`);
const confText = await confDeno.text();
const confDenoParsed = JSONC(confText) as ImportMap;
if(confDenoParsed.importMap) if(confDenoParsed.importMap)
{ {
try try
@ -165,160 +72,108 @@ async function Configure(inDevMode:boolean, inLibPath:string)
const confImports = await Deno.readTextFile(confDenoParsed.importMap); const confImports = await Deno.readTextFile(confDenoParsed.importMap);
try try
{ {
output.Imports = JSON.parse(confImports); ImportObject = JSON.parse(confImports);
} }
catch(e) catch(e)
{ {
output.Error = `"importMap" "${confDenoParsed.importMap}" contains invalid JSON`; console.log(`"importMap" "${confDenoParsed.importMap}" contains invalid JSON`);
return output;
} }
} }
catch(e) catch(e)
{ {
output.Error = `"importMap" "${confDenoParsed.importMap}" cannot be found`; console.log(`"importMap" "${confDenoParsed.importMap}" cannot be found`);
return output;
} }
} }
else if(confDenoParsed.imports) else if(confDenoParsed.imports)
{ {
output.Imports = {imports:confDenoParsed.imports}; ImportObject = {imports:confDenoParsed.imports};
} }
if(output.Imports?.imports) if(ImportObject.imports)
{ {
if(inDevMode) const importReact = ImportObject.imports["react"];
{
const importReact = output.Imports.imports["react"];
if(importReact) if(importReact)
{ {
output.Imports.imports["react-original"] = importReact; ImportObject.imports["react-original"] = importReact;
output.Imports.imports["react"] = `/${inLibPath}/react.tsx`; ImportObject.imports["react"] = `/${LibPath}/react.tsx`;
} }
else else
{ {
output.Error = `"imports" configuration does not alias "react"`; console.log(`"imports" configuration does not alias "react"`);
return output;
}
} }
const importIso = output.Imports.imports["@eno/iso"]; const importApp = ImportObject.imports["@eno/app"];
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"];
if(importApp) 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 else
{ {
output.Error = `"@eno/app" entry-point (${importApp}) needs to export a default function to use as the app root.`; console.log(`"imports" configuration does not alias an entry-point component with "@eno/app"`);
return output;
} }
let twindConfig = Iso.CSS; const importIso = ImportObject.imports["@eno/iso"];
if(typeof appImport.CSS == "object") if(importIso)
{ {
twindConfig = {...twindConfig, ...appImport.CSS}; ImportObject.imports["@eno/iso"] = `/${LibPath}/iso.tsx`;
}
try
{
// @ts-ignore
output.TwindInst = Twind.install(twindConfig);
}
catch(e)
{
output.Error = `CSS configuration is malformed`;
return output;
}
} }
else else
{ {
output.Error = `"imports" configuration does not alias an entry-point file as "@eno/app"`;
return output;
} }
Object.entries(ImportObject.imports).forEach(([key, value])=>{
if(value.startsWith("./") && ImportObject.imports)
Object.entries(output.Imports.imports).forEach(([key, value])=>{
if(value.startsWith("./") && output.Imports?.imports)
{ {
output.Imports.imports[key] = value.substring(1); ImportObject.imports[key] = value.substring(1);
} }
}) })
} }
else else
{ {
output.Error = `No "imports" found in configuration`; console.log(`No "imports" found in configuration`);
return output;
} }
} }
catch(e) catch(e)
{ {
output.Error = `error during configuration: ${e}`; console.log(`deno.json not found`);
return output;
}
return output;
} }
const Flags:Record<string, string|boolean> = {};
Deno.args.forEach(arg=>
{
if(arg.startsWith("--"))
{
const kvp = arg.substring(2).split("=");
Flags[kvp[0]] = kvp[1] ? kvp[1] : true;
}
});
let DevMode = Flags.dev ? true : false; Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) =>
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}`);
console.log(`Args seen: `, Flags);
const {Transpileable, TranspileURL, SocketsHandler} = Transpiler(DevMode);
let {Imports, App, TwindInst, Error} = await Configure(DevMode, Path.LibDir);
if(Error)
{ {
console.log(Error);
}
else if(App && TwindInst)
{
Deno.serve({ port: Flags?.port||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);
const pathExt:string|undefined = pathLast?.split(".")[1]; const pathExt:string|undefined = pathLast?.split(".")[1];
const resp = SocketsHandler(_req); console.log(pathParts, pathLast, pathExt);
if(resp){ return resp; }
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 try
{ {
@ -326,7 +181,7 @@ else if(App && TwindInst)
let type = `text/html`; let type = `text/html`;
let body:BodyInit = ``; let body:BodyInit = ``;
const isLib = url.pathname.startsWith(`/${Path.LibDir}/`); const isLib = url.pathname.startsWith(`/${LibPath}/`);
if(Transpileable(url.pathname)) if(Transpileable(url.pathname))
{ {
@ -335,23 +190,23 @@ else if(App && TwindInst)
{ {
body = await TranspileURL(Path.Hosted+url.pathname, url.pathname, true); body = await TranspileURL(Path.Hosted+url.pathname, url.pathname, true);
} }
else if(DevMode && !url.searchParams.get("reload")) else if(!url.searchParams.get("reload"))
{ {
const imp = await import(Path.Active+url.pathname); const imp = await import(Path.Active+url.pathname);
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 "/${Path.LibDir}/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
@ -363,7 +218,7 @@ else if(App && TwindInst)
else if( pathExt ) else if( pathExt )
{ {
type = MIME.typeByExtension(pathExt) || "text/html"; 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(); body = await _fetch.text();
} }
else else
@ -371,9 +226,8 @@ else if(App && TwindInst)
Iso.Fetch.ServerBlocking = []; Iso.Fetch.ServerBlocking = [];
Iso.Fetch.ServerTouched = new Set(); Iso.Fetch.ServerTouched = new Set();
Iso.Fetch.ServerRemove = new Set(); Iso.Fetch.ServerRemove = new Set();
let app = <Iso.Router.Provider url={url}><App/></Iso.Router.Provider>; let app = <Iso.Router.Provider url={url}><Iso.Meta.Provider><App/></Iso.Meta.Provider></Iso.Router.Provider>;
await Prepass(app); await Prepass(app)
Iso.Meta.Stack = [];
let bake = SSR(app); let bake = SSR(app);
while(Iso.Fetch.ServerBlocking.length) while(Iso.Fetch.ServerBlocking.length)
{ {
@ -381,9 +235,8 @@ else if(App && TwindInst)
Iso.Fetch.ServerBlocking = []; Iso.Fetch.ServerBlocking = [];
// at this point, anything that was requested that was not cached, has now been loaded and cached // at this point, anything that was requested that was not cached, has now been loaded and cached
// this next render will use cached resources. using a cached resource (if its "Seed" is true) adds it to the "touched" set. // this next render will use cached resources. using a cached resource (if its "Seed" is true) adds it to the "touched" set.
app = <Iso.Router.Provider url={url}><App/></Iso.Router.Provider>; app = <Iso.Router.Provider url={url}><Iso.Meta.Provider><App/></Iso.Meta.Provider></Iso.Router.Provider>;
await Prepass(app); await Prepass(app)
Iso.Meta.Stack = [];
bake = SSR(app); bake = SSR(app);
} }
@ -395,37 +248,29 @@ else if(App && TwindInst)
}); });
Iso.Fetch.ServerTouched = false; Iso.Fetch.ServerTouched = false;
Iso.Meta.Meta = Iso.Meta.ComputeFinal(Iso.Meta.Stack);
const results = Twind.extract(bake, TwindInst); const results = Twind.extract(bake, TwindInst);
type = `text/html`; type = `text/html`;
body = body =
`<!doctype html> `<!doctype html>
<html lang="en"> <html lang="en">
<head> <head>
<title>${Iso.Meta.Meta.title}</title> <title>${Iso.Meta.Meta.title}</title>
<meta property="og:title" content="${Iso.Meta.Meta.title}">
<meta name="description" content="${Iso.Meta.Meta.description}">
<meta property="og:description" content="${Iso.Meta.Meta.description}">
<meta property="og:image" content="${Iso.Meta.Meta.image}">
<meta property="og:url" content="${Iso.Meta.Meta.canonical}">
<link rel="canonical" href="${Iso.Meta.Meta.canonical}" />
<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(Imports)}</script> <script type="importmap">${JSON.stringify(ImportObject)}</script>
</head> </head>
<body> <body>
<div id="app">${results.html}</div> <div id="app">${results.html}</div>
<script type="module"> <script type="module">
import {hydrate, createElement as H} from "react"; 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 Twind from "https://esm.sh/v115/@twind/core@1.1.3/es2022/core.mjs";
import * as App from "@eno/app"; import {default as App, CSS} from "@eno/app";
import {Router, Fetch, CSS, Meta} from "@eno/iso"; import {Router, Fetch, Meta} from "@eno/iso";
Twind.install(App.CSS ? {...CSS, ...App.CSS} : CSS); Twind.install(CSS);
Fetch.Seed(${JSON.stringify(seed)}); Fetch.Seed(${JSON.stringify(seed)});
const hmrWrap = H( ()=>H(App.default) ); const hmrWrap = H( ()=>H(App) );
hydrate( hydrate(
H(Router.Provider, null, H(Router.Provider, null,
H(Meta.Provider, null, hmrWrap) H(Meta.Provider, null, hmrWrap)
@ -434,7 +279,7 @@ else if(App && TwindInst)
); );
</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"}});
@ -444,5 +289,47 @@ else if(App && TwindInst)
console.log(error); console.log(error);
return new Response(error, {status:404}); 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();
}
} }