split boot option

This commit is contained in:
Seth Trowbridge 2023-04-30 15:11:54 -04:00
parent b18df9ff89
commit 70a0c2e96f
5 changed files with 246 additions and 223 deletions

View File

@ -1,8 +1,20 @@
import * as mod from "https://deno.land/std@0.185.0/path/mod.ts";
import { doSomethingElse } from './a.tsx'; import { doSomethingElse } from './a.tsx';
export function doSomething() { export function doSomething() {
const pathInit = Deno.mainModule;
const pathProj = mod.toFileUrl(Deno.cwd());
console.log(pathInit);
console.log(import.meta.url);
console.log(pathInit.split(pathProj));
console.log("b main?", Deno.mainModule); console.log("b main?", Deno.mainModule);
console.log("deno main?", Deno.cwd());
Deno.env.set("b", "called"); Deno.env.set("b", "called");
console.log("b action"); console.log("b action");

View File

@ -3,7 +3,8 @@ import * as Iso from "@eno/iso";
const Comp = React.lazy(()=>import("./deep/component.tsx")); const Comp = React.lazy(()=>import("./deep/component.tsx"));
export default ()=> Iso.Boot(
()=>
{ {
return <div class="p-4 font-sans"> return <div class="p-4 font-sans">
<Iso.Meta.Metas title="Main Page!"/> <Iso.Meta.Metas title="Main Page!"/>
@ -12,7 +13,7 @@ export default ()=>
<a href="/about">About</a> <a href="/about">About</a>
</nav> </nav>
<h1 class="my-2 font(bold serif) text(3xl)">Title!!</h1> <h1 class="my-2 font(bold serif) text(3xl)">Title!!!!!!</h1>
<h2>suspended:</h2> <h2>suspended:</h2>
<React.Suspense fallback={<div>Loading!</div>}> <React.Suspense fallback={<div>Loading!</div>}>
<Comp/> <Comp/>
@ -33,4 +34,5 @@ export default ()=>
<Iso.Case default><p>404!</p></Iso.Case> <Iso.Case default><p>404!</p></Iso.Case>
</Iso.Switch> </Iso.Switch>
</div>; </div>;
}; }
);

30
lib/boot-client.tsx Normal file
View File

@ -0,0 +1,30 @@
import React, {hydrate} from "react";
import * as Twind from "https://esm.sh/v115/@twind/core@1.1.3/es2022/core.mjs";
import {Router, CSS, Meta} from "@eno/iso";
export function Boot(inApp:()=>React.JSX.Element, inCSS?:object)
{
console.log(inApp, inCSS);
Twind.install(inCSS ? {...CSS, ...inCSS} : CSS);
const HMRWrap =()=> React.createElement(inApp, null, null);
const root = document.querySelector("#app");
if(root)
{
hydrate(
<Router.Provider url={new URL(window.location.href)}>
<Meta.Provider>
<HMRWrap/>
</Meta.Provider>
</Router.Provider>,
root
);
}
else
{
console.log(`no "#app" element is present!`)
}
};

View File

@ -1,15 +1,7 @@
import TWPreTail from "https://esm.sh/v115/@twind/preset-tailwind@1.1.4/es2022/preset-tailwind.mjs"; 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 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 { Boot as _Boot } from "../server.tsx";
import {INIT} from "../server.tsx";
function wrapper()
{
INIT();
}
wrapper();
export const CSS = { export const CSS = {
presets: [TWPreTail(), TWPreAuto()], presets: [TWPreTail(), TWPreAuto()],
@ -22,6 +14,12 @@ if(!window.innerWidth)
} }
*/ */
export function Boot(inApp:React.FunctionComponent, inCSS?:object)
{
_Boot(inApp, inCSS);
}
type MetasInputs = { [Property in MetaKeys]?: string }; type MetasInputs = { [Property in MetaKeys]?: string };
type MetasModeArgs = {concatListed?:boolean; dropUnlisted?:boolean}; type MetasModeArgs = {concatListed?:boolean; dropUnlisted?:boolean};
type MetasStackItem = MetasModeArgs&MetasInputs&{id:string, depth:number} type MetasStackItem = MetasModeArgs&MetasInputs&{id:string, depth:number}

View File

@ -2,16 +2,13 @@ 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 { parse as JSONC} from "https://deno.land/std@0.185.0/jsonc/mod.ts";
import { toFileUrl } from "https://deno.land/std@0.185.0/path/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");
export const INIT =()=> console.log("init!");
/** /**
* Setup a transpiler. * Setup a transpiler.
* @param inDevMode When true, starts a file-watcher * @param inDevMode When true, starts a file-watcher
@ -136,6 +133,7 @@ function Transpiler(inDevMode:boolean)
} }
type ImportMap = {imports?:Record<string, string>, importMap?:string};
/** /**
* Extract all configuration info form a project's deno.jsonc file * Extract all configuration info form a project's deno.jsonc file
* @param inDevMode When true, proxies react to an HMR-enabled version * @param inDevMode When true, proxies react to an HMR-enabled version
@ -144,8 +142,7 @@ function Transpiler(inDevMode:boolean)
*/ */
async function Configure(inDevMode:boolean, inLibPath:string) async function Configure(inDevMode:boolean, inLibPath:string)
{ {
type ImportMap = {imports?:Record<string, string>, importMap?:string}; const output:{Imports?:ImportMap, Error?:string} = {};
const output:{Imports?:ImportMap, App?:React.FunctionComponent, TwindInst?:Twind.Twind, Error?:string} = {};
let ImportObject:ImportMap = {}; let ImportObject:ImportMap = {};
try try
{ {
@ -206,52 +203,6 @@ async function Configure(inDevMode:boolean, inLibPath:string)
return output; 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])=>{ Object.entries(output.Imports.imports).forEach(([key, value])=>{
if(value.startsWith("./") && output.Imports?.imports) if(value.startsWith("./") && output.Imports?.imports)
@ -274,44 +225,58 @@ async function Configure(inDevMode:boolean, inLibPath:string)
return output; return output;
} }
const Flags:Record<string, string|boolean> = {};
Deno.args.forEach(arg=> Deno.args.forEach(arg=>
{ {
if(arg.startsWith("--")) if(arg.startsWith("--"))
{ {
const kvp = arg.substring(2).split("="); const kvp = arg.substring(2).split("=");
Flags[kvp[0]] = kvp[1] ? kvp[1] : true; Deno.env.set(kvp[0], kvp[1] ? kvp[1] : "true");
} }
}); });
let Booted = false; let DevMode = Deno.env.get("dev") ? true : false;
export function Boot(inApp:React.JSX.Element, inCSS?:object)
{
if(Booted){return;}
Booted = true;
}
let DevMode = Flags.dev ? true : false;
let hosted = import.meta.resolve("./"); let hosted = import.meta.resolve("./");
const Path = { const Path = {
Hosted: hosted.substring(0, hosted.length-1), Hosted: hosted.substring(0, hosted.length-1),
Active: `file://${Deno.cwd().replaceAll("\\", "/")}`, Active: `file://${Deno.cwd().replaceAll("\\", "/")}`,
LibDir: "lib" LibDir: "lib",
AppDir: ""
}; };
console.log(Path); console.log(Path);
console.log(`Dev Mode: ${DevMode}`); console.log(`Dev Mode: ${DevMode}`);
console.log(`Args seen: `, Flags); console.log(`Args seen: `, Deno.env.toObject);
let Booted = false;
let TwindInst:Twind.Twind;
export function Boot(inApp:React.FunctionComponent, inCSS?:object)
{
if(Booted){return;}
Booted = true;
const pathInit = Deno.mainModule;
const pathProj = toFileUrl(Deno.cwd());
//@ts-ignore
TwindInst = Twind.install({...Iso.CSS, ...inCSS||{}});
const App = inApp;
Path.AppDir = pathInit.split(pathProj.toString())[1];
Server(App, Path.AppDir, TwindInst);
}
async function Server(App:React.FunctionComponent, AppPath:string, TwindInst:Twind.Twind)
{
const {Transpileable, TranspileURL, SocketsHandler} = Transpiler(DevMode); const {Transpileable, TranspileURL, SocketsHandler} = Transpiler(DevMode);
const {Imports, App, TwindInst, Error} = await Configure(DevMode, Path.LibDir); const {Imports, Error} = await Configure(DevMode, Path.LibDir);
if(Error) if(Error)
{ {
console.log(Error); console.log(Error);
} }
else if(App && TwindInst) else if(App && TwindInst)
{ {
Deno.serve({ port: Flags?.port||3000 }, async(_req:Request) => Deno.serve({ port: Deno.env.get("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("/");
@ -321,6 +286,8 @@ else if(App && TwindInst)
const resp = SocketsHandler(_req); const resp = SocketsHandler(_req);
if(resp){ return resp; } if(resp){ return resp; }
console.log(url.pathname);
try try
{ {
// serve index by default // serve index by default
@ -336,6 +303,28 @@ 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(url.pathname == "/server.tsx")
{
body = `
import {hydrate, createElement as H} from "react";
import * as Twind from "https://esm.sh/v115/@twind/core@1.1.3/es2022/core.mjs";
import {Router, CSS, Meta} from "@eno/iso";
export function Boot(inApp, inCSS)
{
console.log(inApp, inCSS);
Twind.install(inCSS ? {...CSS, ...inCSS} : CSS);
const hmrWrap = H( ()=>H(inApp) );
hydrate(
H(Router.Provider, {url:window.location},
H(Meta.Provider, null, hmrWrap)
),
document.querySelector("#app")
);
}`;
}
else if(DevMode && !url.searchParams.get("reload")) else if(DevMode && !url.searchParams.get("reload"))
{ {
const imp = await import(Path.Active+url.pathname); const imp = await import(Path.Active+url.pathname);
@ -372,7 +361,7 @@ 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)
let bake = SSR(app); let bake = SSR(app);
while(Iso.Fetch.ServerBlocking.length) while(Iso.Fetch.ServerBlocking.length)
@ -381,7 +370,7 @@ 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)
bake = SSR(app); bake = SSR(app);
} }
@ -410,19 +399,10 @@ else if(App && TwindInst)
<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 {Fetch} from "@eno/iso";
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)}); Fetch.Seed(${JSON.stringify(seed)});
const hmrWrap = H( ()=>H(App.default) );
hydrate( import "${AppPath}";
H(Router.Provider, null,
H(Meta.Provider, null, hmrWrap)
),
document.querySelector("#app")
);
</script> </script>
</body> </body>
</html>`; </html>`;
@ -437,3 +417,4 @@ else if(App && TwindInst)
} }
}); });
} }
}