From cdb9b35e687bdd2051d40bb442685a446f2860bf Mon Sep 17 00:00:00 2001 From: Seth Trowbridge Date: Sat, 29 Apr 2023 11:15:54 -0400 Subject: [PATCH 1/6] default configuration for twind --- example/app.tsx | 9 +--- example/{deno.json => deno.jsonc} | 2 +- lib/iso.tsx | 8 ++++ server.tsx | 76 +++++++++++++++++++++++-------- 4 files changed, 66 insertions(+), 29 deletions(-) rename example/{deno.json => deno.jsonc} (84%) diff --git a/example/app.tsx b/example/app.tsx index 2f4abe9..3d6fac1 100644 --- a/example/app.tsx +++ b/example/app.tsx @@ -1,5 +1,3 @@ -import TWPreTail from "https://esm.sh/v115/@twind/preset-tailwind@1.1.4/es2022/preset-tailwind.mjs"; -import TWPreAuto from "https://esm.sh/v115/@twind/preset-autoprefix@1.0.7/es2022/preset-autoprefix.mjs"; import React from "react"; import * as Iso from "@eno/iso"; @@ -30,9 +28,4 @@ export default ()=>

404!

; -}; - -export const CSS = { - presets: [TWPreTail(), TWPreAuto()], - hash:false -}; +}; \ No newline at end of file diff --git a/example/deno.json b/example/deno.jsonc similarity index 84% rename from example/deno.json rename to example/deno.jsonc index ed849e6..19b81ae 100644 --- a/example/deno.json +++ b/example/deno.jsonc @@ -9,6 +9,6 @@ }, "tasks": { "host": "deno run -A --unstable https://deno.land/std@0.181.0/http/file_server.ts", - "dev": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock --config=deno.json 'http://localhost:4507/server.tsx?reload=1'" + "dev": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock --config=deno.jsonc 'http://localhost:4507/server.tsx?reload=1'" } } \ No newline at end of file diff --git a/lib/iso.tsx b/lib/iso.tsx index 1bb54ea..c91cde4 100644 --- a/lib/iso.tsx +++ b/lib/iso.tsx @@ -1,5 +1,13 @@ +import TWPreTail from "https://esm.sh/v115/@twind/preset-tailwind@1.1.4/es2022/preset-tailwind.mjs"; +import TWPreAuto from "https://esm.sh/v115/@twind/preset-autoprefix@1.0.7/es2022/preset-autoprefix.mjs"; import React from "react"; +export const CSS = { + presets: [TWPreTail(), TWPreAuto()], + hash:false +}; + + type Meta = {title:string, description:string, keywords:string, image:string, canonical:string } type MetaKeys = keyof Meta; export const Meta:Meta = { diff --git a/server.tsx b/server.tsx index 385f1ff..1d8ca67 100644 --- a/server.tsx +++ b/server.tsx @@ -1,6 +1,7 @@ import * as ESBuild from 'https://deno.land/x/esbuild@v0.14.45/mod.js'; import * as MIME from "https://deno.land/std@0.180.0/media_types/mod.ts"; import { debounce } from "https://deno.land/std@0.151.0/async/debounce.ts"; +import { parse as JSONC} from "https://deno.land/std@0.185.0/jsonc/mod.ts"; import SSR from "https://esm.sh/v113/preact-render-to-string@6.0.2"; import Prepass from "https://esm.sh/preact-ssr-prepass@1.2.0"; import * as Twind from "https://esm.sh/@twind/core@1.1.3"; @@ -60,11 +61,13 @@ const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=> const LibPath = "lib"; type ImportMap = {imports?:Record, importMap?:string}; +let App, TwindInst; let ImportObject:ImportMap = {}; try { - const confDeno = await fetch(`${Path.Active}/deno.json`); - const confDenoParsed:ImportMap = await confDeno.json(); + const confDeno = await fetch(`${Path.Active}/deno.jsonc`); + const confText = await confDeno.text(); + const confDenoParsed = JSONC(confText) as ImportMap; if(confDenoParsed.importMap) { try @@ -102,16 +105,6 @@ try console.log(`"imports" configuration does not alias "react"`); } - const importApp = ImportObject.imports["@eno/app"]; - if(importApp) - { - - } - else - { - console.log(`"imports" configuration does not alias an entry-point component with "@eno/app"`); - } - const importIso = ImportObject.imports["@eno/iso"]; if(importIso) { @@ -121,6 +114,52 @@ try { } + + const importApp = ImportObject.imports["@eno/app"]; + if(importApp) + { + let appImport + try + { + appImport = await import(Path.Active+importApp); + } + catch(e) + { + console.log(`"@eno/app" entry-point (${importApp}) file not found`) + } + + if(typeof appImport.default == "function" ) + { + App = appImport.default; + } + else + { + console.log(`"@eno/app" entry-point (${importApp}) needs to export a default function to use as the app root.`) + } + + let twindConfig = Iso.CSS; + if(typeof appImport.CSS == "object") + { + twindConfig = {...twindConfig, ...appImport.CSS}; + } + try + { + // @ts-ignore + TwindInst = Twind.install(twindConfig); + } + catch(e) + { + console.log(`CSS configuration is malformed`); + } + + + } + else + { + console.log(`"imports" configuration does not alias an entry-point file as "@eno/app"`); + } + + Object.entries(ImportObject.imports).forEach(([key, value])=>{ if(value.startsWith("./") && ImportObject.imports) { @@ -135,7 +174,7 @@ try } catch(e) { - console.log(`deno.json not found`); + console.log(`error during configuration: ${e}`); } @@ -266,11 +305,11 @@ FileListen("${url.pathname}", reloadHandler);`; @@ -286,9 +325,6 @@ FileListen("${url.pathname}", reloadHandler);`; } }); -import App, {CSS} from "@eno/app"; -const TwindInst = Twind.install(CSS); - const Sockets:Set = new Set(); const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } } From 8917d179ef45fa4307ce29cc298e9d3a0d799241 Mon Sep 17 00:00:00 2001 From: Seth Trowbridge Date: Sat, 29 Apr 2023 11:49:52 -0400 Subject: [PATCH 2/6] configure phase as function --- example/deno.jsonc | 2 +- server.tsx | 584 +++++++++++++++++++++++---------------------- 2 files changed, 306 insertions(+), 280 deletions(-) diff --git a/example/deno.jsonc b/example/deno.jsonc index 19b81ae..c24e154 100644 --- a/example/deno.jsonc +++ b/example/deno.jsonc @@ -9,6 +9,6 @@ }, "tasks": { "host": "deno run -A --unstable https://deno.land/std@0.181.0/http/file_server.ts", - "dev": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock --config=deno.jsonc 'http://localhost:4507/server.tsx?reload=1'" + "dev": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock --config=deno.jsonc 'http://localhost:4507/server.tsx'" } } \ No newline at end of file diff --git a/server.tsx b/server.tsx index 1d8ca67..fd59860 100644 --- a/server.tsx +++ b/server.tsx @@ -60,307 +60,333 @@ const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=> const LibPath = "lib"; -type ImportMap = {imports?:Record, importMap?:string}; -let App, TwindInst; -let ImportObject:ImportMap = {}; -try + + +async function Configure(inDevMode:boolean, inLibPath:string) { - 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 - { - ImportObject = JSON.parse(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}; - } - - if(ImportObject.imports) - { - const importReact = ImportObject.imports["react"]; - if(importReact) - { - ImportObject.imports["react-original"] = importReact; - ImportObject.imports["react"] = `/${LibPath}/react.tsx`; - } - else - { - console.log(`"imports" configuration does not alias "react"`); - } - - const importIso = ImportObject.imports["@eno/iso"]; - if(importIso) - { - ImportObject.imports["@eno/iso"] = `/${LibPath}/iso.tsx`; - } - else - { - - } - - const importApp = ImportObject.imports["@eno/app"]; - if(importApp) - { - let appImport - try - { - appImport = await import(Path.Active+importApp); - } - catch(e) - { - console.log(`"@eno/app" entry-point (${importApp}) file not found`) - } - - if(typeof appImport.default == "function" ) - { - App = appImport.default; - } - else - { - console.log(`"@eno/app" entry-point (${importApp}) needs to export a default function to use as the app root.`) - } - - let twindConfig = Iso.CSS; - if(typeof appImport.CSS == "object") - { - twindConfig = {...twindConfig, ...appImport.CSS}; - } - try - { - // @ts-ignore - TwindInst = Twind.install(twindConfig); - } - catch(e) - { - console.log(`CSS configuration is malformed`); - } - - - } - else - { - console.log(`"imports" configuration does not alias an entry-point file as "@eno/app"`); - } - - - Object.entries(ImportObject.imports).forEach(([key, value])=>{ - if(value.startsWith("./") && ImportObject.imports) - { - ImportObject.imports[key] = value.substring(1); - } - }) - } - else - { - console.log(`No "imports" found in configuration`); - } -} -catch(e) -{ - console.log(`error during configuration: ${e}`); -} - - -Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) => -{ - const url:URL = new URL(_req.url); - const pathParts = url.pathname.substring(1, url.pathname.endsWith("/") ? url.pathname.length-1 : url.pathname.length).split("/"); - const pathLast = pathParts.at(-1); - const pathExt:string|undefined = pathLast?.split(".")[1]; - - console.log(pathParts, pathLast, pathExt); - - console.log(`Request for "${url.pathname}"...`); - - if(_req.headers.get("upgrade") == "websocket") - { - try - { - const { response, socket } = Deno.upgradeWebSocket(_req); - socket.onopen = () => - { - Sockets.add(socket); - console.log("Overwatch: Socket created"); - }; - socket.onclose = () => - { - Sockets.delete(socket); - console.log("Overwatch: Socket deleted"); - }; - socket.onmessage = (e) => {}; - socket.onerror = (e) => console.log("Overwatch: Socket errored:", e); - return response; - } - catch(e) - { - // - } - } - + type ImportMap = {imports?:Record, importMap?:string}; + const output:{Imports?:ImportMap, App?:React.FunctionComponent, TwindInst?:Twind.Twind, Error?:string} = {}; + let ImportObject:ImportMap = {}; try { - // serve index by default - let type = `text/html`; - let body:BodyInit = ``; - - const isLib = url.pathname.startsWith(`/${LibPath}/`); - - if(Transpileable(url.pathname)) + const confDeno = await fetch(`${Path.Active}/deno.jsonc`); + const confText = await confDeno.text(); + const confDenoParsed = JSONC(confText) as ImportMap; + if(confDenoParsed.importMap) { - type = `application/javascript`; - if(isLib) + try { - body = await TranspileURL(Path.Hosted+url.pathname, url.pathname, true); + 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; + } } - else if(!url.searchParams.get("reload")) + catch(e) { - const imp = await import(Path.Active+url.pathname); - const members = []; - 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);`; - + 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 { - body = await TranspileURL(Path.Active+url.pathname, url.pathname, true); + output.Error = `"imports" configuration does not alias "@eno/iso"`; + return output; } - } - // serve static media - else if( pathExt ) - { - type = MIME.typeByExtension(pathExt) || "text/html"; - const _fetch = await fetch((isLib ? Path.Hosted : Path.Active)+url.pathname); - body = await _fetch.text(); - } - else - { - Iso.Fetch.ServerBlocking = []; - Iso.Fetch.ServerTouched = new Set(); - Iso.Fetch.ServerRemove = new Set(); - let app = ; - await Prepass(app) - let bake = SSR(app); - while(Iso.Fetch.ServerBlocking.length) + + const importApp = output.Imports.imports["@eno/app"]; + if(importApp) { - 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 = ; - await Prepass(app) - bake = SSR(app); + 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; + } } - - const seed:Iso.FetchRecord[] = []; - Iso.Fetch.ServerTouched.forEach((record)=>{ - const r:Iso.FetchRecord = {...record}; - delete r.Promise; - seed.push(r); - }); - Iso.Fetch.ServerTouched = false; - - const results = Twind.extract(bake, TwindInst); - - type = `text/html`; - body = -` - - - ${Iso.Meta.title} - - - - - - -
${results.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}); - } -}); - -const Sockets:Set = new Set(); -const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } } - -const FilesChanged:Map = 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 + { + 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 { - Transpiled.delete(key); + output.Error = `No "imports" found in configuration`; + return output; } } - FilesChanged.clear(); -}, 1000); -for await (const event of Deno.watchFs(Deno.cwd())) -{ - event.paths.forEach( path => + catch(e) { - if(Transpileable(path)) + output.Error = `error during configuration: ${e}`; + return output; + } + return output; +} + +const {Imports, App, TwindInst, Error} = await Configure(true, LibPath); + +if(Error) +{ + console.log(Error); +} + +if(App && TwindInst) +{ + Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) => + { + const url:URL = new URL(_req.url); + const 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]; + + console.log(pathParts, pathLast, pathExt); + + console.log(`Request for "${url.pathname}"...`); + + if(_req.headers.get("upgrade") == "websocket") { - FilesChanged.set(path, event.kind); + 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 + { + // serve index by default + let type = `text/html`; + let body:BodyInit = ``; + + const isLib = url.pathname.startsWith(`/${LibPath}/`); + + if(Transpileable(url.pathname)) + { + type = `application/javascript`; + if(isLib) + { + body = await TranspileURL(Path.Hosted+url.pathname, url.pathname, true); + } + else if(!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 "/${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 TranspileURL(Path.Active+url.pathname, url.pathname, true); + } + } + // serve static media + else if( pathExt ) + { + type = MIME.typeByExtension(pathExt) || "text/html"; + const _fetch = await fetch((isLib ? Path.Hosted : Path.Active)+url.pathname); + body = await _fetch.text(); + } + else + { + Iso.Fetch.ServerBlocking = []; + Iso.Fetch.ServerTouched = new Set(); + Iso.Fetch.ServerRemove = new Set(); + let app = ; + await Prepass(app) + 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 = ; + await Prepass(app) + 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; + + const results = Twind.extract(bake, TwindInst); + + type = `text/html`; + body = + ` + + + ${Iso.Meta.title} + + + + + + +
${results.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}); } }); - if(FilesChanged.size) + + const Sockets:Set = new Set(); + const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } } + + const FilesChanged:Map = new Map(); + const ProcessFiles =debounce(async()=> { - ProcessFiles(); + 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(); + } } } \ No newline at end of file From f7f87f8f38112c091c2c44da69ae0cba4f51a8d7 Mon Sep 17 00:00:00 2001 From: Seth Trowbridge Date: Sat, 29 Apr 2023 13:55:37 -0400 Subject: [PATCH 3/6] transpiler function --- server.tsx | 251 ++++++++++++++++++++++++++++------------------------- 1 file changed, 133 insertions(+), 118 deletions(-) diff --git a/server.tsx b/server.tsx index fd59860..29bb34b 100644 --- a/server.tsx +++ b/server.tsx @@ -8,60 +8,132 @@ import * as Twind from "https://esm.sh/@twind/core@1.1.3"; import React from "react"; import * as Iso from "@eno/iso"; -let hosted = import.meta.resolve("./"); -const Path = { - Hosted:hosted.substring(0, hosted.length-1), - Active:`file://${Deno.cwd().replaceAll("\\", "/")}` -}; -console.log(Path); - -const Transpiled = new Map(); -const Transpileable =(inFilePath:string):boolean=> +/** + * Setup a transpiler. + * @param inDevMode When true, starts a file-watcher + * @returns + */ +function Transpiler(inDevMode:boolean) { - let dotIndex = inFilePath.length-4; - if(inFilePath[dotIndex] !== ".") + const Transpiled = new Map(); + const Transpileable =(inFilePath:string):boolean=> { - if(inFilePath[++dotIndex] !== ".") + let dotIndex = inFilePath.length-4; + if(inFilePath[dotIndex] !== ".") { - return false; + if(inFilePath[++dotIndex] !== ".") + { + return false; + } + } + + if(inFilePath[dotIndex+2] == "s") + { + const first = inFilePath[dotIndex+1]; + return (first == "t" || first == "j"); + } + + return false; + }; + const Transpile =async(inCode:string, inKey:string):Promise=> + { + const transpile = await ESBuild.transform(inCode, inDevMode ? { loader: "tsx", sourcemap:"inline", minify: false, sourcefile:inKey} : {loader:"tsx", minify: true}); + + Transpiled.set(inKey, transpile.code); + return transpile.code; + }; + type Transpiler = (inPath:string, inKey:string, inCheck?:boolean)=>Promise; + const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=> + { + if(inCheck) + { + const cached = Transpiled.get(inKey); + if(cached) + { + return cached; + } + } + let body = await fetch(inPath); + let text = await body.text(); + return Transpile(text, inKey); + }; + + const Sockets:Set = new Set(); + const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } } + const SocketsHandler = inDevMode ? (_req:Request)=> + { + if(_req.headers.get("upgrade") == "websocket") + { + try + { + const { response, socket } = Deno.upgradeWebSocket(_req); + socket.onopen = () => Sockets.add(socket); + socket.onclose = () => Sockets.delete(socket); + socket.onmessage = (e) => {}; + socket.onerror = (e) => console.log("Socket errored:", e); + return response; + } + catch(e) + { + // + } + } + return false; + } + : + ()=>false; + + const watcher =async()=> + { + const FilesChanged:Map = new Map(); + const ProcessFiles =debounce(async()=> + { + for await (const [path, action] of FilesChanged) + { + const key = path.substring(Deno.cwd().length).replaceAll("\\", "/"); + if(action != "remove") + { + await TranspileURL(Path.Active+key, key, false); + SocketsBroadcast(key); + } + else + { + Transpiled.delete(key); + } + } + FilesChanged.clear(); + }, 1000); + for await (const event of Deno.watchFs(Deno.cwd())) + { + event.paths.forEach( path => + { + if(Transpileable(path)) + { + FilesChanged.set(path, event.kind); + } + }); + if(FilesChanged.size) + { + ProcessFiles(); + } } } - if(inFilePath[dotIndex+2] == "s") + if(inDevMode) { - const first = inFilePath[dotIndex+1]; - return (first == "t" || first == "j"); + watcher().then(()=>{console.log("done watching");}); } - return false; -}; -const Transpile =async(inCode:string, inKey:string):Promise=> -{ - const transpile = await ESBuild.transform(inCode, { loader: "tsx", sourcemap:"inline", minify:true, sourcefile:inKey}); - - Transpiled.set(inKey, transpile.code); - return transpile.code; -}; -type Transpiler = (inPath:string, inKey:string, inCheck?:boolean)=>Promise; -const TranspileURL:Transpiler =async(inPath, inKey, inCheck)=> -{ - if(inCheck) - { - const cached = Transpiled.get(inKey); - if(cached) - { - return cached; - } - } - let body = await fetch(inPath); - let text = await body.text(); - return Transpile(text, inKey); -}; - - -const LibPath = "lib"; + 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, importMap?:string}; @@ -194,14 +266,23 @@ async function Configure(inDevMode:boolean, inLibPath:string) return output; } -const {Imports, App, TwindInst, Error} = await Configure(true, LibPath); +let DevMode = true; +let hosted = import.meta.resolve("./"); +const Path = { + Hosted: hosted.substring(0, hosted.length-1), + Active: `file://${Deno.cwd().replaceAll("\\", "/")}`, + LibDir: "lib" +}; +console.log(Path); +console.log(`Dev Mode: ${DevMode}`); +const {Transpileable, TranspileURL, SocketsHandler} = Transpiler(DevMode); +const {Imports, App, TwindInst, Error} = await Configure(DevMode, Path.LibDir); if(Error) { console.log(Error); } - -if(App && TwindInst) +else if(App && TwindInst) { Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) => { @@ -209,35 +290,9 @@ if(App && TwindInst) 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]; - - console.log(pathParts, pathLast, pathExt); - - console.log(`Request for "${url.pathname}"...`); - - if(_req.headers.get("upgrade") == "websocket") - { - try - { - const { response, socket } = Deno.upgradeWebSocket(_req); - socket.onopen = () => - { - Sockets.add(socket); - console.log("Overwatch: Socket created"); - }; - socket.onclose = () => - { - Sockets.delete(socket); - console.log("Overwatch: Socket deleted"); - }; - socket.onmessage = (e) => {}; - socket.onerror = (e) => console.log("Overwatch: Socket errored:", e); - return response; - } - catch(e) - { - // - } - } + + const resp = SocketsHandler(_req); + if(resp){ return resp; } try { @@ -245,7 +300,7 @@ if(App && TwindInst) let type = `text/html`; let body:BodyInit = ``; - const isLib = url.pathname.startsWith(`/${LibPath}/`); + const isLib = url.pathname.startsWith(`/${Path.LibDir}/`); if(Transpileable(url.pathname)) { @@ -261,7 +316,7 @@ if(App && TwindInst) for( const key in imp ) { members.push(key); } body = ` - import {FileListen} from "/${LibPath}/hmr.tsx"; + 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} }; @@ -282,7 +337,7 @@ if(App && TwindInst) else if( pathExt ) { type = MIME.typeByExtension(pathExt) || "text/html"; - const _fetch = await fetch((isLib ? Path.Hosted : Path.Active)+url.pathname); + const _fetch = await fetch((Path.Active)+url.pathname); body = await _fetch.text(); } else @@ -349,44 +404,4 @@ if(App && TwindInst) return new Response(error, {status:404}); } }); - - const Sockets:Set = new Set(); - const SocketsBroadcast =(inData:string)=>{ for (const socket of Sockets){ socket.send(inData); } } - - const FilesChanged:Map = 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(); - } - } } \ No newline at end of file From 1b16b087886a4aacc355731fc2234d57f78021f1 Mon Sep 17 00:00:00 2001 From: Seth Trowbridge Date: Sat, 29 Apr 2023 20:16:28 -0400 Subject: [PATCH 4/6] auto booter --- example/deno.jsonc | 6 +++--- lib/iso.tsx | 4 ++++ server.tsx | 3 +++ 3 files changed, 10 insertions(+), 3 deletions(-) diff --git a/example/deno.jsonc b/example/deno.jsonc index c24e154..dc2d7a4 100644 --- a/example/deno.jsonc +++ b/example/deno.jsonc @@ -2,13 +2,13 @@ "compilerOptions": {"lib": ["deno.window", "dom"]}, "imports": { - "react": "https://esm.sh/preact@10.13.2/compat", + "react": "https://esm.sh/stable/preact@10.13.2/compat", + "preact": "https://esm.sh/stable/preact@10.13.2/", "@deep/": "./deep/", "@eno/app": "./app.tsx", "@eno/iso": "http://localhost:4507/lib/iso.tsx" }, "tasks": { - "host": "deno run -A --unstable https://deno.land/std@0.181.0/http/file_server.ts", - "dev": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock --config=deno.jsonc 'http://localhost:4507/server.tsx'" + "dev": "deno run -A --unstable --reload=http://localhost:4507/ --no-lock app.tsx" } } \ No newline at end of file diff --git a/lib/iso.tsx b/lib/iso.tsx index c91cde4..b5b1e98 100644 --- a/lib/iso.tsx +++ b/lib/iso.tsx @@ -7,6 +7,10 @@ export const CSS = { hash:false }; +if(Deno) +{ + import(import.meta.resolve("../../server.tsx")).then(()=>{console.log("...imported!");}); +} type Meta = {title:string, description:string, keywords:string, image:string, canonical:string } type MetaKeys = keyof Meta; diff --git a/server.tsx b/server.tsx index 29bb34b..d79d382 100644 --- a/server.tsx +++ b/server.tsx @@ -8,6 +8,8 @@ import * as Twind from "https://esm.sh/@twind/core@1.1.3"; import React from "react"; import * as Iso from "@eno/iso"; +Deno.env.set("initialized", "true"); + /** * Setup a transpiler. * @param inDevMode When true, starts a file-watcher @@ -275,6 +277,7 @@ const Path = { }; console.log(Path); console.log(`Dev Mode: ${DevMode}`); +console.log(`Args seen: ${Deno.args}`); const {Transpileable, TranspileURL, SocketsHandler} = Transpiler(DevMode); const {Imports, App, TwindInst, Error} = await Configure(DevMode, Path.LibDir); From 48bb1eff2b5f868ae3ca89a25280d630caef233a Mon Sep 17 00:00:00 2001 From: Seth Trowbridge Date: Sat, 29 Apr 2023 20:43:03 -0400 Subject: [PATCH 5/6] flag parsing, jsx:automatic, fix ss check --- lib/iso.tsx | 2 +- server.tsx | 26 ++++++++++++++++++++------ 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/lib/iso.tsx b/lib/iso.tsx index b5b1e98..5a56087 100644 --- a/lib/iso.tsx +++ b/lib/iso.tsx @@ -7,7 +7,7 @@ export const CSS = { hash:false }; -if(Deno) +if(!window.innerWidth) { import(import.meta.resolve("../../server.tsx")).then(()=>{console.log("...imported!");}); } diff --git a/server.tsx b/server.tsx index d79d382..c81d508 100644 --- a/server.tsx +++ b/server.tsx @@ -1,4 +1,4 @@ -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 { 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"; @@ -39,7 +39,11 @@ function Transpiler(inDevMode:boolean) }; const Transpile =async(inCode:string, inKey:string):Promise=> { - const transpile = await ESBuild.transform(inCode, inDevMode ? { loader: "tsx", sourcemap:"inline", minify: false, sourcefile:inKey} : {loader:"tsx", 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); return transpile.code; @@ -268,7 +272,17 @@ async function Configure(inDevMode:boolean, inLibPath:string) return output; } -let DevMode = true; +const Flags:Record = {}; +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), @@ -277,7 +291,7 @@ const Path = { }; console.log(Path); console.log(`Dev Mode: ${DevMode}`); -console.log(`Args seen: ${Deno.args}`); +console.log(`Args seen: `, Flags); const {Transpileable, TranspileURL, SocketsHandler} = Transpiler(DevMode); const {Imports, App, TwindInst, Error} = await Configure(DevMode, Path.LibDir); @@ -287,7 +301,7 @@ if(Error) } else if(App && TwindInst) { - Deno.serve({ port: Deno.args[0]||3000 }, async(_req:Request) => + 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("/"); @@ -312,7 +326,7 @@ else if(App && TwindInst) { body = await TranspileURL(Path.Hosted+url.pathname, url.pathname, true); } - else if(!url.searchParams.get("reload")) + else if(DevMode && !url.searchParams.get("reload")) { const imp = await import(Path.Active+url.pathname); const members = []; From 4d8dcf53c5c07a2e2ddaa731bb7d779e8d28b6c5 Mon Sep 17 00:00:00 2001 From: Seth Trowbridge Date: Sat, 29 Apr 2023 21:15:14 -0400 Subject: [PATCH 6/6] fix merge errors --- example/app.tsx | 9 ++- example/deep/component.tsx | 4 +- example/deno.jsonc | 2 +- lib/iso.tsx | 130 +++++++++++++++++++++++++++---------- server.tsx | 11 +++- 5 files changed, 113 insertions(+), 43 deletions(-) diff --git a/example/app.tsx b/example/app.tsx index 3d6fac1..8a7cd9e 100644 --- a/example/app.tsx +++ b/example/app.tsx @@ -6,7 +6,7 @@ const Comp = React.lazy(()=>import("./deep/component.tsx")); export default ()=> { return
- +