diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 0000000..a00fbf1 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,17 @@ +{ + // 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": "Debug Serve Mode", + "type": "node", + "cwd": "${workspaceFolder}/example", + "runtimeExecutable": "deno", + "runtimeArgs": ["task", "debug"], + "attachSimplePort": 9229 + } + ] +} \ No newline at end of file diff --git a/.vscode/settings.json b/.vscode/settings.json index b003be2..8675ad5 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,5 +1,4 @@ { "deno.enable": true, - "deno.unstable": true, - "deno.config": "./deno.json" + "deno.unstable": true } \ No newline at end of file diff --git a/api b/api new file mode 100644 index 0000000..777ecae --- /dev/null +++ b/api @@ -0,0 +1,4 @@ +export default (req:Request):Response|false=> +{ + return false; +} \ No newline at end of file diff --git a/app b/app new file mode 100644 index 0000000..2308168 --- /dev/null +++ b/app @@ -0,0 +1 @@ +export default ()=>{}; \ No newline at end of file diff --git a/deno.json b/deno.json index 61c231c..f8d9679 100644 --- a/deno.json +++ b/deno.json @@ -7,11 +7,13 @@ { "react":"https://esm.sh/preact@10.15.1/compat", "react-original":"https://esm.sh/preact@10.15.1/compat", - "able/": "http://localhost:1234/" + ">able/": "http://localhost:4507/" }, "tasks": { - "local": "deno run -A --no-lock ./run-local.tsx --port=1234", - "serve": "deno run -A --no-lock ./run-serve.tsx --port=1234" + "local": "deno run -A --reload=http://localhost --no-lock ./run-local.tsx --port=1234", + "serve": "deno run -A --reload=http://localhost --no-lock ./run-serve.tsx --port=1234", + "debug": "deno run -A --reload=http://localhost --inspect-wait --no-lock ./run-serve.tsx --port=1234", + "deploy":"deno run -A --no-lock --reload=http://localhost http://localhost:4507/run-deploy.tsx" } } \ No newline at end of file diff --git a/example/.env b/example/.env new file mode 100644 index 0000000..6a7678a --- /dev/null +++ b/example/.env @@ -0,0 +1 @@ +DENO_DEPLOY_TOKEN=1 \ No newline at end of file diff --git a/example/api.tsx b/example/api.tsx new file mode 100644 index 0000000..75d913f --- /dev/null +++ b/example/api.tsx @@ -0,0 +1,4 @@ +export default (inReq:Request)=> +{ + return false; +} \ No newline at end of file diff --git a/example/app.tsx b/example/app.tsx index 0f99425..e2f7de8 100644 --- a/example/app.tsx +++ b/example/app.tsx @@ -1,4 +1,4 @@ -import { Router, Switch, Case } from "able/iso-elements.tsx"; +import { Router, Switch, Case } from ">able/iso-elements.tsx"; import React from "react"; @@ -39,7 +39,7 @@ export default ()=> return
-

Title

+

Title?????

subtitle

diff --git a/example/deno.json b/example/deno.json index a352b2f..9155bc1 100644 --- a/example/deno.json +++ b/example/deno.json @@ -3,12 +3,15 @@ "imports": { "react": "https://esm.sh/preact@10.15.1/compat", - "able/": "http://localhost:1234/", - "entry": "./app.tsx" + ">able/": "http://localhost:4507/", + ">able/app": "./app.tsx", + ">able/api": "./api.tsx" }, "tasks": { - "local": "deno run -A --no-lock --reload=http://localhost:1234 http://localhost:1234/run-local.tsx", - "serve": "deno run -A --no-lock --reload=http://localhost:1234 http://localhost:1234/run-serve.tsx" + "local": "deno run --config=deno.json -A --no-lock --reload=http://localhost:4507 http://localhost:4507/run-local.tsx", + "serve": "deno run --config=deno.json -A --no-lock --reload=http://localhost:4507 http://localhost:4507/run-serve.tsx", + "deploy":"deno run -A --no-lock --reload=http://localhost:4507 http://localhost:4507/run-deploy.tsx", + "debug": "deno run --config=deno.json -A --inspect-wait --no-lock --reload=http://localhost:4507 http://localhost:4507/run-serve.tsx" } } \ No newline at end of file diff --git a/example/dyn-test.tsx b/example/dyn-test.tsx deleted file mode 100644 index 63ca671..0000000 --- a/example/dyn-test.tsx +++ /dev/null @@ -1,15 +0,0 @@ - -import * as Util from "@able/"; -import * as React from "react"; -import {createElement} from "react/client"; - -import('react').then((module) => { - console.log(module); -}); - - -function unimport(n:number) -{ - return n; -} -unimport(123) \ No newline at end of file diff --git a/run-deploy.tsx b/run-deploy.tsx index 478419c..89af979 100644 --- a/run-deploy.tsx +++ b/run-deploy.tsx @@ -1,4 +1,4 @@ -import { load } from "https://deno.land/std@0.194.0/dotenv/mod.ts"; +import * as Env from "https://deno.land/std@0.194.0/dotenv/mod.ts"; import { parse } from "https://deno.land/std@0.194.0/flags/mod.ts"; @@ -47,18 +47,12 @@ try { console.log("Runing deploy!"); const serveScript = import.meta.resolve("./run-serve.tsx"); - console.log("Serve script:", serveScript); let arg = parse(Deno.args); - let env = await load(); + let env = await Env.load(); let useToken = await collect("DENO_DEPLOY_TOKEN", arg, env); let useProject = await collect("DENO_DEPLOY_PROJECT", arg, env); - let useEntry = await collect("DENO_DEPLOY_ENTRY", arg, env); - - Deno.env.set("DENO_DEPLOY_TOKEN", useToken || ""); - Deno.env.set("DENO_DEPLOY_ENTRY", useEntry || ""); - const command = new Deno.Command( `deno`, @@ -70,6 +64,8 @@ try "https://deno.land/x/deploy/deployctl.ts", "deploy", `--project=${useProject}`, + `--config=deno.json`, + `--token=${useToken}`, serveScript ], stdin: "piped", diff --git a/run-local.tsx b/run-local.tsx index b1b1943..6cf1af7 100644 --- a/run-local.tsx +++ b/run-local.tsx @@ -1,4 +1,4 @@ -import {Configure, Transpile, Extension} from "./run-serve.tsx"; +import {Configure, Transpile, Extension, Root} from "./run-serve.tsx"; import * as Collect from "./hmr-static.tsx"; const SocketsLive:Set = new Set(); @@ -22,57 +22,48 @@ Configure({ Remap: (inImports, inConfig)=> { inImports["react-original"] = inImports["react"]; - inImports["react"] = import.meta.resolve(`./hmr-react.tsx`); + inImports["react"] = `/>able/hmr-react.tsx`; return inImports; }, async Serve(inReq, inURL, inExt, inMap, inConfig) { - if(Transpile.Check(inExt) && !inURL.searchParams.get("reload")) + if(!inURL.pathname.startsWith(encodeURI("/>"))) { - -// const imp = await import(inConfig.Proxy+inURL.pathname); -// const members = []; -// for( const key in imp ) { members.push(key); } -// -// const code =` -//import {FileListen} from "${import.meta.resolve(`./hmr-listen.tsx`)}"; -//import * as Import from "${inURL.pathname}?reload=0"; -//${ members.map(m=>`let proxy_${m} = Import.${m}; export { proxy_${m} as ${m} };`).join("\n") } -//FileListen("${inURL.pathname}", (updatedModule)=> -//{ -// ${ members.map(m=>`proxy_${m} = updatedModule.${m};`).join("\n") } -//});` - - // we dont need to add ?reload= because this fetch is by way the file system not the hosted url - const [local, foreign] = await Collect.FileExports(inConfig.Proxy+inURL.pathname); - const code =` -import {FileListen} from "${import.meta.resolve(`./hmr-listen.tsx`)}"; -import * as Import from "${inURL.pathname}?reload=0"; -${ local.map(m=>`let proxy_${m} = Import.${m}; export { proxy_${m} as ${m} };`).join("\n") } -FileListen("${inURL.pathname}", (updatedModule)=> -{ - ${ local.map(m=>`proxy_${m} = updatedModule.${m};`).join("\n") } -}); -${ foreign.join(";\n") } -` - - return new Response(code, {headers:{"content-type":"application/javascript"}}); - } - - - if(inReq.headers.get("upgrade") == "websocket") - { - try + if(Transpile.Check(inExt) && !inURL.searchParams.get("reload")) { - const { response, socket } = Deno.upgradeWebSocket(inReq); - socket.onopen = () => SocketsLive.add(socket); - socket.onclose = () => SocketsLive.delete(socket); - socket.onmessage = (e) => {}; - socket.onerror = (e) => console.log("Socket errored:", e); - return response; + + // we dont need to add ?reload= because this fetch is by way the file system not the hosted url + const [local, foreign] = await Collect.FileExports(Root+inURL.pathname); + const code =` + import {FileListen} from ">able/hmr-listen.tsx"; + import * as Import from "${inURL.pathname}?reload=0"; + ${ local.map(m=>`let proxy_${m} = Import.${m}; export { proxy_${m} as ${m} };`).join("\n") } + FileListen("${inURL.pathname}", (updatedModule)=> + { + ${ local.map(m=>`proxy_${m} = updatedModule.${m};`).join("\n") } + }); + ${ foreign.join(";\n") } + ` + + return new Response(code, {headers:{"content-type":"application/javascript"}}); } - catch(e){ /**/ } + + + if(inReq.headers.get("upgrade") == "websocket") + { + try + { + const { response, socket } = Deno.upgradeWebSocket(inReq); + socket.onopen = () => SocketsLive.add(socket); + socket.onclose = () => SocketsLive.delete(socket); + socket.onmessage = (e) => {}; + socket.onerror = (e) => console.log("Socket errored:", e); + return response; + } + catch(e){ /**/ } + } } + } }); @@ -95,7 +86,7 @@ const Watcher =async()=> const key = path.substring(Deno.cwd().length).replaceAll("\\", "/"); if(action != "remove") { - const tsx = await Transpile.Fetch(`file://${Deno.cwd().replaceAll("\\", "/")}`+key, key, true); + const tsx = await Transpile.Fetch(Root+key, key, true); tsx && SocketsSend(key); } else diff --git a/run-serve.tsx b/run-serve.tsx index 55ff51f..73a748f 100644 --- a/run-serve.tsx +++ b/run-serve.tsx @@ -1,6 +1,10 @@ import * as MIME from "https://deno.land/std@0.180.0/media_types/mod.ts"; import * as SWCW from "https://esm.sh/@swc/wasm-web@1.3.62"; +import Api from ">able/api"; + + +export const Root = new URL(`file://${Deno.cwd().replaceAll("\\", "/")}`).toString(); Deno.args.forEach(arg=> { @@ -14,10 +18,11 @@ Deno.args.forEach(arg=> type DenoConfig = {imports:Record}; const ImportMap:DenoConfig = {imports:{}}; let ImportMapOriginal = {}; +let ImportMapProxies:Record = {}; const ImportMapReload =async()=> { let json:DenoConfig; - const path = Configuration.Proxy+"/deno.json"; + const path = Root+"/deno.json"; try { const resp = await fetch(path); @@ -41,17 +46,32 @@ const ImportMapReload =async()=> json.imports["react/"] = json.imports["react"]+"/"; } - if(!json.imports["entry"]) + if(!json.imports["able:app"]) { - console.log(`"entry" specifier not defined in import map.`); + console.log(`"able:app" specifier not defined in import map.`); } + + ImportMapProxies = {}; Object.entries(json.imports).forEach(([key, value])=> { if(value.startsWith("./")) { json.imports[key] = value.substring(1); } + if(key.startsWith(">")) + { + if(value.startsWith("./")) + { + ImportMapProxies[encodeURI(key)] = value.substring(1); + json.imports[key] = value.substring(1); + } + else + { + ImportMapProxies["/"+encodeURI(key)] = value; + json.imports[key] = "/"+key; + } + } }); ImportMap.imports = Configuration.Remap(json.imports, Configuration); @@ -59,11 +79,10 @@ const ImportMapReload =async()=> type CustomHTTPHandler = (inReq:Request, inURL:URL, inExt:string|false, inMap:{imports:Record}, inConfig:Configuration)=>void|false|Response|Promise; type CustomRemapper = (inImports:Record, inConfig:Configuration)=>Record; -type Configuration = {Proxy:string, Allow:string, Reset:string, SWCOp:SWCW.Options, Serve:CustomHTTPHandler, Shell:CustomHTTPHandler, Remap:CustomRemapper}; -type ConfigurationArgs = {Proxy?:string, Allow?:string, Reset?:string, SWCOp?:SWCW.Options, Serve?:CustomHTTPHandler, Shell?:CustomHTTPHandler, Remap?:CustomRemapper}; +type Configuration = {Allow:string, Reset:string, SWCOp:SWCW.Options, Serve:CustomHTTPHandler, Shell:CustomHTTPHandler, Remap:CustomRemapper}; +type ConfigurationArgs = {Allow?:string, Reset?:string, SWCOp?:SWCW.Options, Serve?:CustomHTTPHandler, Shell?:CustomHTTPHandler, Remap?:CustomRemapper}; let Configuration:Configuration = { - Proxy: new URL(`file://${Deno.cwd().replaceAll("\\", "/")}`).toString(), Allow: "*", Reset: "/clear-cache", async Serve(inReq, inURL, inExt, inMap, inConfig){}, @@ -73,8 +92,6 @@ let Configuration:Configuration = }, Shell(inReq, inURL, inExt, inMap, inConfig) { - const parts = Deno.mainModule.split(inConfig.Proxy); - return new Response( ` @@ -86,8 +103,8 @@ let Configuration:Configuration =

`, {status:200, headers:{"content-type":"text/html"}}); @@ -133,6 +150,7 @@ export const Transpile = return size; }, /** + * DONT USE * Converts dynamic module imports in to static, also can resolve paths with an import map */ async Patch(inPath:string, inKey:string, inMap?:DenoConfig) @@ -263,17 +281,46 @@ export const Configure =(config:ConfigurationArgs)=> } await ImportMapReload(); -await SWCW.default(); +try +{ + await SWCW.default(); +} +catch(e) +{ + console.log("swc init error:", e); +} + + const server = Deno.serve({port:parseInt(Deno.env.get("port")||"8000")}, async(req: Request)=> { const url:URL = new URL(req.url); const ext = Extension(url.pathname); const headers = {"content-type":"application/json", "Access-Control-Allow-Origin": Configuration.Allow, "charset":"UTF-8"}; + let proxy = Root + url.pathname; - // cache-reset route - if(url.pathname === Configuration.Reset) + if(url.pathname.includes("/__")) { - return new Response(`{"cleared":${Transpile.Clear()}}`, {headers}); + return new Response(`{"error":"unmatched route", "path":"${url.pathname}"}`, {status:404, headers}); + } + + // proxy imports + if(url.pathname.startsWith(encodeURI("/>"))) + { + let bestMatch=""; + for(let key in ImportMapProxies) + { + if(url.pathname.startsWith(key) && key.length > bestMatch.length) + { + bestMatch = key; + } + } + if(bestMatch.length) + { + const match = ImportMapProxies[bestMatch]; + const path = url.pathname.substring(bestMatch.length); + proxy = path ? match + path : Root + match; + + } } // allow for custom handler @@ -283,42 +330,17 @@ const server = Deno.serve({port:parseInt(Deno.env.get("port")||"8000")}, async(r return custom; } + const api = Api(req); + if(api) + { + return api; + } + // transpileable files if(Transpile.Check(ext)) { - let code; - let path; - let file; - if( req.headers.get("user-agent")?.startsWith("Deno") || url.searchParams.has("deno") ) - { - try - { - path = Configuration.Proxy + ExtensionPrefix(url.pathname, "deno"); - console.log("looking for", path); - file = await fetch(path) as Response; - if(file.ok) - { - code = await file.text(); - } - else - { - throw new Error("404"); - } - } - catch(e) - { - path = Configuration.Proxy + url.pathname; - console.log("falling back to", path); - file = await fetch(path); - code = await file.text(); - } - } - else - { - path = Configuration.Proxy + url.pathname; - code = await Transpile.Fetch(path, url.pathname); - } - + console.log("transpiling:", proxy); + const code = await Transpile.Fetch(proxy, url.pathname); if(code) { return new Response(code, {headers:{...headers, "content-type":"application/javascript"}} ); @@ -335,13 +357,19 @@ const server = Deno.serve({port:parseInt(Deno.env.get("port")||"8000")}, async(r } } + // cache-reset route + if(url.pathname === Configuration.Reset) + { + return new Response(`{"cleared":${Transpile.Clear()}}`, {headers}); + } + // all other static files if(ext) { try { const type = MIME.typeByExtension(ext); - const file = await fetch(Configuration.Proxy + url.pathname); + const file = await fetch(proxy); return new Response(file.body, {headers:{...headers, "content-type":type||""}}); } catch(e) @@ -352,4 +380,5 @@ const server = Deno.serve({port:parseInt(Deno.env.get("port")||"8000")}, async(r return new Response(`{"error":"unmatched route", "path":"${url.pathname}"}`, {status:404, headers}); -}); \ No newline at end of file +}); +