Compare commits

...

55 Commits
hmr ... master

Author SHA1 Message Date
7b0d713906 fix meta-merging logic
oops :(
2023-05-14 09:05:19 -04:00
35bd15ed6e Merge pull request 'ssr-metas' (#26) from ssr-metas into master
Reviewed-on: #26
2023-05-14 07:47:59 -04:00
6f86ebae7a allow Isp.Switch to have multiple child elements 2023-05-14 07:44:35 -04:00
31c9f8fc07 server side fixes 2023-05-14 07:26:18 -04:00
b51e469632 re-compute stack 2023-05-13 23:21:22 -04:00
260c156b8f starting meta tags other than title 2023-05-13 14:06:28 -04:00
945800bb22 better debugging 2023-05-10 22:50:27 -04:00
4bd02c6d6d Merge pull request 'hmr fixes' (#25) from redo-boot into master
Reviewed-on: #25
2023-05-06 14:28:41 -04:00
de4f7608ba get rid of junk 2023-05-06 14:27:20 -04:00
8a1b7e7dbd hmr fixes
allow page refresh, add keep-alive ping
2023-05-06 09:51:55 -04:00
d3f08a67a0 Merge pull request 'modes' (#23) from modes into master
Reviewed-on: #23
2023-04-29 21:30:28 -04:00
79904123f7 Merge branch 'master' into modes 2023-04-29 21:27:19 -04:00
4d8dcf53c5 fix merge errors 2023-04-29 21:15:14 -04:00
48bb1eff2b flag parsing, jsx:automatic, fix ss check 2023-04-29 20:43:03 -04:00
1b16b08788 auto booter 2023-04-29 20:16:28 -04:00
f7f87f8f38 transpiler function 2023-04-29 14:29:04 -04:00
8917d179ef configure phase as function 2023-04-29 11:49:52 -04:00
cdb9b35e68 default configuration for twind 2023-04-29 11:16:43 -04:00
6e4b7af16f Merge pull request 'misc' (#22) from misc into master
Reviewed-on: #22
2023-04-29 06:58:52 -04:00
c8fbebe351 fix meta ordering and rendering 2023-04-25 20:41:22 -04:00
fafdeffeeb metas reorgnaization started 2023-04-23 22:17:39 -04:00
4613ff38e2 improved click handler 2023-04-23 08:31:42 -04:00
8ab67be4d8 Merge pull request 'issue/fetch' (#21) from issue/fetch into master
Reviewed-on: #21
2023-04-22 15:18:27 -04:00
4f594c2168 fix missing hmr wrapper 2023-04-22 15:02:53 -04:00
8b21aba029 fetch config 2023-04-22 13:48:32 -04:00
63137a7726 fix flickering 2023-04-22 12:08:58 -04:00
bdeb51a940 control client seeding 2023-04-22 06:22:53 -04:00
1ed3e0abaa server record clearing 2023-04-21 22:21:04 -04:00
26cb46923f seed the client cache 2023-04-21 20:27:37 -04:00
866eb9b26d ssr data batches 2023-04-20 21:07:26 -04:00
7847410f3e fetch hook started 2023-04-19 20:56:30 -04:00
4730cdec3e fetch cache started 2023-04-18 22:22:59 -04:00
d9c5b83f26 Merge pull request '#16 issue/router' (#18) from issue/router into master
Reviewed-on: #18
2023-04-18 19:39:56 -04:00
101a5d2218 cleanup 2023-04-16 21:33:09 -04:00
8ed6a4b029 switch/case rendering 2023-04-15 12:39:08 -04:00
ca556e3a68 link clicking 2023-04-14 21:41:01 -04:00
64a4a82ac8 allow for params and route 2023-04-14 06:58:12 -04:00
06266d7ca6 router started 2023-04-13 22:23:04 -04:00
4d3760d92c standardize of fetch for reading files 2023-04-08 12:51:09 -04:00
77fa38f531 Merge pull request '#12 issue/iso-components' (#13) from issue/iso-components into master
Reviewed-on: #13
2023-04-07 21:41:21 -04:00
0a5d96ce7a route fixes #12 2023-04-07 21:36:51 -04:00
767e681640 #8 render title 2023-04-06 23:44:27 -04:00
91a2fe76c5 metas started 2023-04-05 23:34:20 -04:00
bf9b56c10d Merge pull request '#10 issue/iso-file-serving' (#11) from issue/iso-file-serving into master
Reviewed-on: #11
2023-04-05 21:10:58 -04:00
a36cdc13c0 serve iso correctly
this reverts the prev commits woes
2023-04-05 21:05:22 -04:00
5d06bc99d1 "self-hosting" 2023-04-05 20:05:21 -04:00
d9bc3901a0 Merge pull request '#6 issue/ssr-simple' (#7) from issue/ssr-simple into master
Reviewed-on: #7
2023-04-05 11:33:03 -04:00
cd7599dcc9 move twind config into @eno.app
that may need to change later
2023-04-03 23:35:10 -04:00
fe02721687 hard-coded twind config for now 2023-04-02 14:16:58 -04:00
c70ab52a1f Merge pull request '#3 issue/ssr-simple' (#5) from issue/ssr-simple into master
Reviewed-on: #5
2023-04-02 00:08:48 -04:00
4ff0da09a3 add example, fix preact ssr version issue 2023-04-02 00:06:27 -04:00
9b6b7cd8c8 basic ssr 2023-04-01 22:45:33 -04:00
5efb25541b Merge pull request 'SethTrowbridge/eno#2 add @eno/app mapping' (#4) from issue/entry into master
Reviewed-on: #4
2023-04-01 15:39:05 -04:00
c92407ab47 add @eno/app mapping 2023-04-01 15:34:50 -04:00
5f9f03459c Merge pull request 'hmr' (#1) from hmr into master
Reviewed-on: #1
2023-04-01 11:13:22 -04:00
11 changed files with 1006 additions and 256 deletions

23
.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,23 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"request": "launch",
"name": "Launch Program",
"type": "node",
"program": "${workspaceFolder}/server.tsx",
"cwd": "${workspaceFolder}",
"runtimeExecutable": "deno.exe",
"runtimeArgs": [
"run",
"--unstable",
"--inspect-wait",
"--allow-all"
],
"attachSimplePort": 9229
}
]
}

View File

@ -1,14 +0,0 @@
{
"compilerOptions": {"lib": [
"deno.window", "DOM"
]},
"imports": {
"react-original": "https://esm.sh/react@18.2.0"
},
"tasks":
{
"install": "deno install -f -A --unstable --no-lock -n eno server.tsx",
"run": "deno run -A --unstable --no-lock server.tsx",
"host": "deno run -A --unstable https://deno.land/std@0.181.0/http/file_server.ts"
}
}

18
deno.jsonc Normal file
View File

@ -0,0 +1,18 @@
{
"compilerOptions": {"lib": [
"deno.window", "DOM"
]},
"imports": {
"react": "https://esm.sh/preact@10.13.2/compat",
"react-original": "https://esm.sh/preact@10.13.2/compat",
"@eno/app": "./example/app.tsx",
"@eno/iso": "./lib/iso.tsx"
},
"tasks":
{
"install": "deno install -f -A --unstable --no-lock -n eno server.tsx",
"host": "deno run -A --unstable https://deno.land/std@0.181.0/http/file_server.ts",
"example": "cd example && pwd && deno task dev"
}
}

52
deno.lock Normal file
View File

@ -0,0 +1,52 @@
{
"version": "2",
"remote": {
"https://deno.land/std@0.151.0/async/debounce.ts": "564273ef242bcfcda19a439132f940db8694173abffc159ea34f07d18fc42620",
"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/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/preact.mjs": "365fab897381f4f403f859c5d12939084560545567108cc90dae901bbe892578",
"https://esm.sh/v113/preact-render-to-string@6.0.2": "9e27e8724b3e53ba3d006146efa7ac0d6764672e4cd7a2fb5738412526c2b16d",
"https://esm.sh/v113/preact-render-to-string@6.0.2/deno/preact-render-to-string.mjs": "09ead691b3745189a4171a6ee0948592c7a862b1bf1a97fe651fb34f88eabe3b",
"https://esm.sh/v113/preact-render-to-string@6.0.2/src/index.d.ts": "3df00ff7e5f6dc9d2d6b944a88c2e541b098c0e559bd3a918732f3aa35acf1af",
"https://esm.sh/v113/preact@10.13.2/src/index.d.ts": "65398710de6aa0a07412da79784e05e6e96763f51c7c91b77344d2d0af06385c",
"https://esm.sh/v113/preact@10.13.2/src/jsx.d.ts": "9ac9b82c199fa7b04748807d750eba1a106c0be52041b8617416f88d6fc0a257",
"https://esm.sh/v115/@twind/core@1.1.3/es2022/core.mjs": "937e906c390266871215f71372af7fadf98274fb47670a7e1e8cf98e775357a8",
"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"
}
}

66
example/app.tsx Normal file
View File

@ -0,0 +1,66 @@
import React from "react";
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"));
export default ()=>
{
const [stack] = React.useContext(Iso.Meta.Context);
return <div class="p-4 font-sans">
<Iso.Meta.Metas title="Main Page!" description="its great"/>
<nav class="p-4">
<a class="text-red-500" href="/">Home</a>
<a href="/about">About</a>
</nav>
<h1 class="my-2 font(bold serif) text(3xl)">Title!!</h1>
<h2>suspended:</h2>
<React.Suspense fallback={<div>Loading!</div>}>
<Comp/>
</React.Suspense>
<Iso.Switch>
<Iso.Case value="/">
<p>thing1</p>
<p>thing2</p>
</Iso.Case>
<Iso.Case value="page">
<Iso.Switch>
<Iso.Case value="about-us">
<>
<Iso.Meta.Metas title="About US" concatListed=" | "/>
About us!
</>
</Iso.Case>
<Iso.Case default>sorry no page</Iso.Case>
</Iso.Switch>
</Iso.Case>
<Iso.Case value="lol/idk">lol/idk</Iso.Case>
<Iso.Case default>
<>
<Iso.Meta.Metas description="a 404 has occurred"/>
<p>404!</p>
</>
</Iso.Case>
</Iso.Switch>
</div>;
};

View File

@ -0,0 +1,23 @@
import React from "react";
import * as Iso from "@eno/iso";
export default ()=>
{
const [countGet, countSet] = React.useState(1);
const [routeGet, routeSet] = Iso.Router.Consumer();
type CatFact = {fact:string, length:number}|undefined;
const [Data, Updating] = Iso.Fetch.Use(`https://catfact.ninja/fact`);
console.log("component.tsx render!!")
return <div class="p-4 text-red-500">
<Iso.Meta.Metas title="Component!" description="components can set metas"/>
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>
<a href="/page/about-us" className="p-2 text(lg blue-500) font-bold">a link</a>
<p>Data:{Data && (Data as CatFact)?.fact}</p>
<p>Status:{Updating?'loading':'done'}</p>
</div>;
};

13
example/deno.jsonc Normal file
View File

@ -0,0 +1,13 @@
{
"compilerOptions": {"lib": ["deno.window", "dom"]},
"imports":
{
"react": "https://esm.sh/stable/preact@10.13.2/compat",
"@eno/app": "./app.tsx",
"@eno/iso": "http://localhost:4507/lib/iso.tsx"
},
"tasks": {
"dev": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock app.tsx --dev",
"run": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock app.tsx"
}
}

View File

@ -1,7 +1,8 @@
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>>;
new WebSocket("ws://"+document.location.host).addEventListener('message', (event) => const socket:WebSocket = new WebSocket("ws://"+document.location.host);
socket.addEventListener('message', (event) =>
{ {
let handlers = listeners.get(event.data)??[]; let handlers = listeners.get(event.data)??[];
reloads++; reloads++;
@ -13,6 +14,7 @@ new WebSocket("ws://"+document.location.host).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)=>
{ {

409
lib/iso.tsx Normal file
View File

@ -0,0 +1,409 @@
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, { 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 MetasModeArgs = {concatListed?:string; dropUnlisted?:boolean};
type MetasStackItem = MetasModeArgs&MetasInputs&{id:string, depth:number}
type Meta = {title:string, description:string, keywords:string, image:string, canonical:string }
type MetaKeys = keyof Meta;
export const Meta =
{
Stack:[] as MetasStackItem[],
Meta: {
title:"",
description:"",
keywords:"",
image:"",
canonical:""
} 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[]>]),
Provider({children}:{children:Children})
{
const binding = React.useState([] as MetasStackItem[]);
type MetaDOM = {description:NodeListOf<Element>, title:NodeListOf<Element>, image:NodeListOf<Element>, url:NodeListOf<Element>};
const refElements = React.useRef(null as null | MetaDOM);
React.useEffect(()=>
{
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>;
},
Metas({concatListed=undefined, dropUnlisted=false, ...props}:MetasModeArgs&MetasInputs):null
{
const id = React.useId();
const [, metasSet] = React.useContext(Meta.Context);
const {depth} = React.useContext(SwitchContext);
React.useEffect(()=>{
metasSet((m)=>{
console.log(`adding meta`, props, depth);
const clone = [...m];
let i;
for(i=clone.length-1; i>-1; i--)
{
if(clone[i].depth <= depth)
{
break;
}
}
clone.splice(i+1, 0, {id, depth, concatListed, dropUnlisted, ...props});
return clone;
});
return ()=>
{
metasSet((m)=>{
const clone = [...m];
const ind = clone.findIndex(i=>i.id === id);
if(ind > -1)
{
console.log(`removing meta`, props, depth);
clone.splice(ind, 1);
}
return clone;
});
};
}, []);
React.useEffect(()=>{
metasSet((m)=>{
const clone = [...m];
const ind = clone.findIndex(i=>i.id === id);
if(ind > -1)
{
console.log(`updating meta`, props, depth);
clone[ind] = {...clone[ind], ...props};
}
return clone;
});
}, Object.keys(props).map( (key) => props[key as MetaKeys] ));
if(!window.innerWidth && props.title)
{
Meta.Stack.push({id, depth, concatListed, dropUnlisted, ...props});
}
return null;
}
};
export type Children = string | number | React.JSX.Element | React.JSX.Element[];
type RoutePath = Array<string>;
type RouteParams = Record<string, string|number|boolean>;
type RouteState = {URL:URL, Path:RoutePath, Params:RouteParams, Anchor:string};
type RouteContext = [Route:RouteState, Update:(inPath?:RoutePath, inParams?:RouteParams, inAnchor?:string)=>void];
type RouteProps = {children:Children, url?:URL };
export const Router = {
Parse(url:URL):RouteState
{
const Path = url.pathname.substring(1, url.pathname.endsWith("/") ? url.pathname.length-1 : url.pathname.length).split("/");
const Params:RouteParams = {};
new URLSearchParams(url.search).forEach((k, v)=> Params[k] = v);
const Anchor = url.hash.substring(1);
return {URL:url, Path, Params, Anchor} as RouteState;
},
Context:React.createContext([{URL:new URL("https://original.route/"), Path:[], Params:{}, Anchor:""}, ()=>{}] as RouteContext),
Provider(props:RouteProps)
{
const [routeGet, routeSet] = React.useState(Router.Parse(props.url || new URL(document.location.href)));
const [dirtyGet, dirtySet] = React.useState(true);
const routeUpdate:RouteContext[1] =(inPath, inParams, inAnchor)=>
{
const clone = new URL(routeGet.URL);
inPath && (clone.pathname = inPath.join("/"));
inParams && (clone.search = new URLSearchParams(inParams as Record<string, string>).toString());
routeSet({
URL:clone,
Path: inPath || routeGet.Path,
Params: inParams || routeGet.Params,
Anchor: inAnchor || routeGet.Anchor
});
};
// when the state changes, update the page url
React.useEffect(()=> dirtyGet ? dirtySet(false) : history.pushState({...routeGet, URL:undefined}, "", routeGet.URL), [routeGet.URL.href]);
React.useEffect(()=>{
history.replaceState({...routeGet, URL:undefined}, "", routeGet.URL);
window.addEventListener("popstate", ({state})=>
{
dirtySet(true);
routeUpdate(state.Path, state.Params, state.Anchor);
});
document.addEventListener("click", e=>
{
const t = e.target as HTMLAnchorElement;
const path = e.composedPath() as HTMLAnchorElement[];
for(let i=0; i<path.length; i++)
{
if(path[i].href)
{
const u = new URL(t.href);
if(u.origin == document.location.origin)
{
e.preventDefault();
const parts = Router.Parse(u);
routeUpdate(parts.Path, parts.Params, parts.Anchor);
}
return;
}
}
})
}, []);
return <Router.Context.Provider value={[routeGet, routeUpdate]}>{props.children}</Router.Context.Provider>;
},
Consumer()
{
return React.useContext(Router.Context);
}
};
type SwitchContext = {depth:number, keys:Record<string, string>};
export const SwitchContext = React.createContext({depth:0, keys:{}} as SwitchContext);
export const Switch =({children}:{children:Children})=>
{
let fallback = null;
if(Array.isArray(children))
{
const contextSelection = React.useContext(SwitchContext);
const [contextRoute] = Router.Consumer();
const routeSegment = contextRoute.Path.slice(contextSelection.depth);
const checkChild =(inChild:{props:{value?:string}})=>
{
if(inChild?.props?.value)
{
const parts = inChild.props.value.split("/");
if(parts.length > routeSegment.length)
{
return false;
}
const output:SwitchContext = {depth:contextSelection.depth+parts.length, keys:{}};
for(let i=0; i<parts.length; i++)
{
const partRoute = routeSegment[i];
const partCase = parts[i];
if(partCase[0] == ":")
{
output.keys[partCase.substring(1)] = partRoute;
}
else if(partCase != "*" && partCase != partRoute)
{
return false;
}
}
return output;
}
return false;
}
for(let i=0; i<children.length; i++)
{
const childCase = children[i];
const childCaseChildren = childCase.props?.__args?.slice(2) || childCase.props.children;
const newContextValue = checkChild(childCase);
if(newContextValue)
{
return <SwitchContext.Provider value={newContextValue}>{childCaseChildren}</SwitchContext.Provider>
}
if(childCase?.props?.default && !fallback)
{
//console.log(routeSegment);
fallback = childCaseChildren;
}
}
}
return fallback;
};
export const Case =({children, value}:{children:Children, value?:string, default?:true})=>null;
export const useRouteVars =()=> React.useContext(SwitchContext).keys;
export type FetchCachOptions = {CacheFor:number, CacheOnServer:boolean, DelaySSR:boolean, Seed:boolean};
export type FetchRecord = {URL:string, Promise?:Promise<FetchRecord>, CachedAt:number, Error?:string, JSON?:object} & FetchCachOptions;
type FetchGuide = [Record:FetchRecord, Init:boolean, Listen:boolean];
export type FetchHookState = [Data:undefined|object, Updating:boolean];
export const Fetch = {
Cache:new Map() as Map<string, FetchRecord>,
ServerBlocking:false as false|Promise<FetchRecord>[],
ServerTouched:false as false|Set<FetchRecord>,
ServerRemove:false as false|Set<FetchRecord>,
Seed(seed:FetchRecord[])
{
seed.forEach(r=>{
//r.Promise = Promise.resolve(r);
Fetch.Cache.set(r.URL, r)
});
},
DefaultOptions:{CacheFor:60, CacheOnServer:true, DelaySSR:true, Seed:true} as FetchCachOptions,
Request(URL:string, Init?:RequestInit|null, CacheFor:number = 60, CacheOnServer:boolean = true, DelaySSR:boolean = true, Seed:boolean = true):FetchGuide
{
let check = Fetch.Cache.get(URL);
const load =(inCheck:FetchRecord)=>
{
Fetch.Cache.set(URL, inCheck);
inCheck.CachedAt = 0;
inCheck.Promise = fetch(URL, Init?Init:undefined).then(resp=>resp.json()).then((json)=>{
inCheck.JSON = json;
inCheck.CachedAt = new Date().getTime();
//console.log(`...cached!`);
return inCheck;
});
return inCheck;
};
if(!check)
{
// not in the cache
// - listen
//console.log(`making new cache record...`);
return [load({URL, CacheFor, CachedAt:0, CacheOnServer, DelaySSR, Seed}), false, true];
}
else if(check.CachedAt == 0)
{
// loading started but not finished
// - listen
// - possibly init if there is something in JSON
//console.log(`currently being cached...`);
return [check, check.JSON ? true : false, true];
}
else
{
//console.log(`found in cache...`);
let secondsAge = (new Date().getTime() - check.CachedAt)/1000;
if(secondsAge > check.CacheFor)
{
// cached but expired
// - listen
// - init
//console.log(`...outdated...`);
return [load(check), true, true];
}
else
{
// cached and ready
// - init
//console.log(`...retrieved!`);
return [check, true, false];
}
}
},
Use(URL:string, Init?:RequestInit|null, Options?:FetchCachOptions)
{
const config = {...Fetch.DefaultOptions, ...Options};
const [receipt, init, listen] = Fetch.Request(URL, Init, config.CacheFor, config.CacheOnServer, config.DelaySSR, config.Seed);
const initialState:FetchHookState = init ? [receipt.JSON, listen] : [undefined, true];
const [cacheGet, cacheSet] = React.useState(initialState);
if(Fetch.ServerBlocking && Fetch.ServerTouched && config.DelaySSR) // if server-side rendering
{
if(listen) // if the request is pending
{
receipt.Promise && Fetch.ServerBlocking.push(receipt.Promise); // add promise to blocking list
return [undefined, listen] as FetchHookState; // no need to return any actual data while waiting server-side
}
else // if request is ready
{
receipt.Seed && Fetch.ServerTouched.add(receipt); // add record to client seed list (if specified in receipt.seed)
return [receipt.JSON, false] as FetchHookState;
}
}
React.useEffect(()=>
{
if(listen)
{
//const receipt = Fetch.Request(URL, Init, CacheFor, CacheOnServer, DelaySSR);
receipt.Promise?.then(()=>cacheSet([receipt.JSON, receipt.CachedAt === 0]));
}
}
, []);
return cacheGet;
}
};

View File

@ -73,4 +73,5 @@ const ProxyState =(arg)=>
export * from "react-original"; export * from "react-original";
export { ProxyCreate as createElement, ProxyState as useState }; export { ProxyCreate as createElement, ProxyState as useState };
export default {...ReactParts.default, createElement:ProxyCreate, useState:ProxyState}; export const isProxy = true;
export default {...ReactParts.default, createElement:ProxyCreate, useState:ProxyState, isProxy:true};

View File

@ -1,10 +1,25 @@
import * as ESBuild from 'https://deno.land/x/esbuild@v0.14.45/mod.js'; import * as ESBuild from 'https://deno.land/x/esbuild@v0.17.4/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 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";
const Transpiled = new Map(); Deno.env.set("initialized", "true");
const Transpileable =(inFilePath:string):boolean=>
/**
* Setup a transpiler.
* @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] !== ".")
{ {
@ -21,16 +36,21 @@ const Transpileable =(inFilePath:string):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, { loader: "tsx", sourcemap: "inline", minify:true }); const transpile = await ESBuild.transform(inCode, inDevMode ? { loader: "tsx", sourcemap:"inline", minify: false, 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 TranspileFS: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);
@ -39,141 +59,24 @@ const TranspileFS:Transpiler =async(inPath, inKey, inCheck)=>
return cached; return cached;
} }
} }
const body = await Deno.readTextFile(inPath); let body = await fetch(inPath);
return Transpile(body, inKey);
};
const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=>
{
if(inCheck)
{
const cached = Transpiled.get(inKey);
if(cached)
{
return cached;
}
}
const path = import.meta.resolve(`.${inPath}`);
let body = await fetch(path);
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 LibPath = "lib"; const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } }
type ImportMap = {imports?:Record<string, string>, importMap?:string}; const SocketsHandler = inDevMode ? (_req:Request)=>
let ImportString = ``;
let ImportObject:ImportMap = {};
try
{
const confDeno = await Deno.readTextFile(Deno.cwd()+"/deno.json");
const confDenoParsed:ImportMap = JSON.parse(confDeno);
if(confDenoParsed.importMap)
{ {
try
{
const confImports = await Deno.readTextFile(confDenoParsed.importMap);
try
{
ImportObject = JSON.parse(confImports);
ImportString = confImports;
}
catch(e)
{
console.log(`"importMap" "${confDenoParsed.importMap}" contains invalid JSON`);
}
}
catch(e)
{
console.log(`"importMap" "${confDenoParsed.importMap}" cannot be found`);
}
}
else if(confDenoParsed.imports)
{
ImportObject = {imports:confDenoParsed.imports};
ImportString = JSON.stringify(ImportObject);
}
if(ImportObject.imports)
{
const importReact = ImportObject.imports?.["react"];
if(importReact)
{
ImportObject.imports["react-original"] = importReact;
ImportObject.imports["react"] = `./${LibPath}/react.tsx`;
ImportString = JSON.stringify(ImportObject);
}
else
{
console.log(`"imports" configuration does not alias "react"`);
}
}
else
{
console.log(`No "imports" found in configuration`);
}
}
catch(e)
{
console.log(`deno.json not found`);
}
const Index = `
<!doctype html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script type="importmap">${ImportString}</script>
<script async src="https://ga.jspm.io/npm:es-module-shims@1.5.1/dist/es-module-shims.js" crossorigin="anonymous"></script>
</head>
<body>
<div id="app">Loading</div>
<script type="module">
import * as TW from "https://esm.sh/@twind/core@1.0.1";
import TWPreTail from "https://esm.sh/@twind/preset-tailwind@1.0.1";
import TWPreAuto from "https://esm.sh/@twind/preset-autoprefix@1.0.1";
const Configure = {presets: [TWPreTail(), TWPreAuto()]};
const ShadowDOM = document.querySelector("#app").attachShadow({mode: "open"});
const ShadowDiv = document.createElement("div");
const ShadowCSS = document.createElement("style");
ShadowDOM.append(ShadowCSS);
ShadowDOM.append(ShadowDiv);
TW.observe(TW.twind(Configure, TW.cssom(ShadowCSS)), ShadowDiv);
import App from "./app.tsx";
import {render, createElement as H} from "react";
render(H(()=>H(App)), ShadowDiv);
</script>
</body>
</html>
`;
Deno.serve({ port: 3000 }, async(_req:Request) =>
{
const url:URL = new URL(_req.url);
const fsPath = Deno.cwd()+url.pathname;
console.log(`Request for "${url.pathname}"...`);
if(_req.headers.get("upgrade") == "websocket") if(_req.headers.get("upgrade") == "websocket")
{ {
try try
{ {
const { response, socket } = Deno.upgradeWebSocket(_req); const { response, socket } = Deno.upgradeWebSocket(_req);
socket.onopen = () => socket.onopen = () => Sockets.add(socket);
{ socket.onclose = () => Sockets.delete(socket);
Sockets.add(socket);
console.log("Overwatch: Socket created");
};
socket.onclose = () =>
{
Sockets.delete(socket);
console.log("Overwatch: Socket deleted");
};
socket.onmessage = (e) => {}; socket.onmessage = (e) => {};
socket.onerror = (e) => console.log("Overwatch: Socket errored:", e); socket.onerror = (e) => console.log("Socket errored:", e);
return response; return response;
} }
catch(e) catch(e)
@ -181,102 +84,41 @@ Deno.serve({ port: 3000 }, async(_req:Request) =>
// //
} }
} }
return false;
try
{
// serve index by default
let type = `text/html`;
let body:BodyInit = Index;
const isLib = url.pathname.startsWith(`/${LibPath}/`)
// serve .tsx .jsx .ts .js
if(Transpileable(url.pathname))
{
type = `application/javascript`;
if(isLib)
{
body = await TranspileURL(url.pathname, url.pathname, true);
} }
else if(!url.searchParams.get("reload")) :
{ ()=>false;
const path = `file://${Deno.cwd().replaceAll("\\", "/")+url.pathname}`;
console.log(path);
const imp = await import(path); let reloads = 0;
const members = []; const watcher =async()=>
for( const key in imp ) { members.push(key); }
body =
`
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);`;
}
else
{ {
body = await TranspileFS(fsPath, url.pathname, true); const FilesChanged:Map<string, string> = new Map();
} const ProcessFiles =debounce(async()=>
}
// serve static media
else if( url.pathname.endsWith("/") === false)
{ {
type = MIME.typeByExtension(url.pathname.substring(url.pathname.lastIndexOf("."))) || "text/html";
if(isLib)
{
const _fetch = await fetch(import.meta.resolve(`.${url.pathname}`));
body = await _fetch.text();
}
else
{
body = await Deno.readFile(fsPath);
}
}
return new Response(body, {headers:{"content-type":type as string}});
}
catch(error)
{
console.log(error);
return new Response(error, {status:404});
}
});
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) for await (const [path, action] of FilesChanged)
{ {
const key = path.substring(Deno.cwd().length).replaceAll("\\", "/"); const key = path.substring(Deno.cwd().length).replaceAll("\\", "/");
console.log(key, action);
if(action != "remove") if(action != "remove")
{ {
await TranspileFS(path, key, false); if(Imports?.imports)
console.log(` ...cached "${key}"`); {
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); SocketsBroadcast(key);
} }
else else
{ {
Transpiled.delete(key) Transpiled.delete(key);
} }
} }
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))
@ -288,4 +130,319 @@ for await (const event of Deno.watchFs(Deno.cwd()))
{ {
ProcessFiles(); 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 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;
if(confDenoParsed.importMap)
{
try
{
const confImports = await Deno.readTextFile(confDenoParsed.importMap);
try
{
output.Imports = JSON.parse(confImports);
}
catch(e)
{
output.Error = `"importMap" "${confDenoParsed.importMap}" contains invalid JSON`;
return output;
}
}
catch(e)
{
output.Error = `"importMap" "${confDenoParsed.importMap}" cannot be found`;
return output;
}
}
else if(confDenoParsed.imports)
{
output.Imports = {imports:confDenoParsed.imports};
}
if(output.Imports?.imports)
{
if(inDevMode)
{
const importReact = output.Imports.imports["react"];
if(importReact)
{
output.Imports.imports["react-original"] = importReact;
output.Imports.imports["react"] = `/${inLibPath}/react.tsx`;
}
else
{
output.Error = `"imports" configuration does not alias "react"`;
return output;
}
}
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"];
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;
}
let twindConfig = Iso.CSS;
if(typeof appImport.CSS == "object")
{
twindConfig = {...twindConfig, ...appImport.CSS};
}
try
{
// @ts-ignore
output.TwindInst = Twind.install(twindConfig);
}
catch(e)
{
output.Error = `CSS configuration is malformed`;
return output;
}
}
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)
{
output.Imports.imports[key] = value.substring(1);
}
})
}
else
{
output.Error = `No "imports" found in configuration`;
return output;
}
}
catch(e)
{
output.Error = `error during configuration: ${e}`;
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;
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 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; }
try
{
// serve index by default
let type = `text/html`;
let body:BodyInit = ``;
const isLib = url.pathname.startsWith(`/${Path.LibDir}/`);
if(Transpileable(url.pathname))
{
type = `application/javascript`;
if(isLib)
{
body = await TranspileURL(Path.Hosted+url.pathname, url.pathname, true);
}
else if(DevMode && !url.searchParams.get("reload"))
{
const imp = await import(Path.Active+url.pathname);
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)=>
{
${ members.map(m=>`proxy_${m} = updatedModule.${m};`).join("\n") }
};
FileListen("${url.pathname}", reloadHandler);`;
}
else
{
body = await TranspileURL(Path.Active+url.pathname, url.pathname, true);
}
}
// serve static media
else if( pathExt )
{
type = MIME.typeByExtension(pathExt) || "text/html";
const _fetch = await fetch((Path.Active)+url.pathname);
body = await _fetch.text();
}
else
{
Iso.Fetch.ServerBlocking = [];
Iso.Fetch.ServerTouched = new Set();
Iso.Fetch.ServerRemove = new Set();
let app = <Iso.Router.Provider url={url}><App/></Iso.Router.Provider>;
await Prepass(app);
Iso.Meta.Stack = [];
let bake = SSR(app);
while(Iso.Fetch.ServerBlocking.length)
{
await Promise.all(Iso.Fetch.ServerBlocking);
Iso.Fetch.ServerBlocking = [];
// 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.
app = <Iso.Router.Provider url={url}><App/></Iso.Router.Provider>;
await Prepass(app);
Iso.Meta.Stack = [];
bake = SSR(app);
}
const seed:Iso.FetchRecord[] = [];
Iso.Fetch.ServerTouched.forEach((record)=>{
const r:Iso.FetchRecord = {...record};
delete r.Promise;
seed.push(r);
});
Iso.Fetch.ServerTouched = false;
Iso.Meta.Meta = Iso.Meta.ComputeFinal(Iso.Meta.Stack);
const results = Twind.extract(bake, TwindInst);
type = `text/html`;
body =
`<!doctype html>
<html lang="en">
<head>
<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 charset="utf-8"/>
<style data-twind>${results.css}</style>
<script type="importmap">${JSON.stringify(Imports)}</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, Meta} from "@eno/iso";
Twind.install(App.CSS ? {...CSS, ...App.CSS} : CSS);
Fetch.Seed(${JSON.stringify(seed)});
const hmrWrap = H( ()=>H(App.default) );
hydrate(
H(Router.Provider, null,
H(Meta.Provider, null, hmrWrap)
),
document.querySelector("#app")
);
</script>
</body>
</html>`;
}
return new Response(body, {headers:{"content-type":type as string, "Access-Control-Allow-Origin":"*", charset:"utf-8"}});
}
catch(error)
{
console.log(error);
return new Response(error, {status:404});
}
});
} }