Compare commits

...

6 Commits

Author SHA1 Message Date
91542c30a5 forgot some stuff 2024-04-23 15:35:23 -04:00
9d31b9a08c add outer/inner debugging 2024-04-23 12:44:22 -04:00
bef45f9107 workflow, misc edits 2024-01-26 17:21:47 -05:00
9fbd811101 cirectory cleanup 2023-11-06 17:05:40 -05:00
8d89cebe12 bake working 2023-11-06 15:45:47 -05:00
f0c34f461e baker started 2023-11-06 12:18:44 -05:00
14 changed files with 211 additions and 202 deletions

28
.github/workflows/deploy.yml vendored Normal file
View File

@ -0,0 +1,28 @@
name: Deploy to GitHub Pages
on:
push:
branches:
- master
jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v2
- name: Setup Deno
uses: denolib/setup-deno@v2
with:
deno-version: 1.8
- name: Run Deno Script
run: deno run -A --no-lock cli.tsx baker
- name: Deploy to GitHub Pages
uses: peaceiris/actions-gh-pages@v3
with:
github_token: ${{ secrets.GITHUB_TOKEN }}
publish_dir: ./.bake

9
.vscode/launch.json vendored
View File

@ -5,13 +5,18 @@
"version": "0.2.0",
"configurations": [
{
"name": "Host Process",
"request": "launch",
"name": "Debug Serve Mode",
"type": "node",
"cwd": "${workspaceFolder}/example",
"runtimeExecutable": "deno",
"runtimeArgs": ["task", "debug"],
"attachSimplePort": 9229
},
{
"name": "Subprocess",
"request": "attach",
"type": "node",
"port": 9230
}
]
}

View File

@ -1,3 +0,0 @@
{
"deno.enable": true
}

View File

@ -3,7 +3,9 @@ import { parse as JSONC } from "https://deno.land/x/jsonct@v0.1.0/mod.ts";
type ConfigCheck = {path?:string, text?:string, json?:Record<string, string|Record<string, string|string[]>>};
type ConfigCheckPair = [config:ConfigCheck, imports:ConfigCheck];
/** The full url location of checker.tsx wherever it is hosted */
export const RootHost = import.meta.resolve("./");
/** The file system url where deno is currently running */
export const Root = new URL(`file://${Deno.cwd().replaceAll("\\", "/")}`).toString();
export async function HuntConfig()
{
@ -58,7 +60,7 @@ export async function HuntConfig()
}
}
let imports:ConfigCheck = {};
const imports:ConfigCheck = {};
if(json && json.imports)
{
// config.imports
@ -116,7 +118,7 @@ export async function Install(file:string, overrideName?:string, handler?:(conte
export async function Check()
{
let [config, imports] = await HuntConfig();
const [config, imports] = await HuntConfig();
try
{
@ -167,9 +169,9 @@ export async function Check()
const importMap = imports.json.imports as Record<string, string>;
const bake =async(obj:ConfigCheck)=> await Deno.writeTextFile(Deno.cwd()+"/"+obj.path, JSON.stringify(obj.json, null, "\t"));
importMap["react"] = `https://esm.sh/preact@10.18.1/compat`;
importMap["react/"] = `https://esm.sh/preact@10.18.1/compat/`;
importMap["@preact/signals"] = `https://esm.sh/@preact/signals@1.2.1`;
importMap["react"] = `https://esm.sh/preact@10.20.2/compat`;
importMap["react/"] = `https://esm.sh/preact@10.20.2/compat/`;
importMap["@preact/signals"] = `https://esm.sh/@preact/signals@1.2.3`;
importMap["@twind/core"] = `https://esm.sh/@twind/core@1.1.3`;
importMap[">able/"] = `${RootHost}`;
if(!importMap[">able/app.tsx"])

24
cli.tsx
View File

@ -4,7 +4,7 @@ import { RootHost, HuntConfig, Install, Check } from "./checker.tsx";
let arg = await Arg.parse(Deno.args);
let env = await Env.load();
const collect =async(inKey:string, inArg:Record<string, string>, inEnv:Record<string, string>):Promise<string|undefined>=>
const collect =(inKey:string, inArg:Record<string, string>, inEnv:Record<string, string>):string|undefined=>
{
const scanArg = inArg[inKey];
const scanEnvFile = inEnv[inKey];
@ -87,13 +87,12 @@ if(arg._.length)
}
case "debug" :
{
await SubProcess(["run", `-A`, `--no-lock`, `--config=${config.path}`, `--inspect-brk`, RootHost+"run.tsx", "--dev", ...Deno.args]);
await SubProcess(["run", `-A`, `--no-lock`, `--config=${config.path}`, `--inspect-wait=127.0.0.1:9230`, RootHost+"run.tsx", "--dev", ...Deno.args]);
break;
}
case "serve" :
{
const args = ["run", `-A`, `--no-lock`, `--config=${config.path}`, RootHost+"run.tsx", ...Deno.args];
console.log("args are", args);
await SubProcess(args);
break;
}
@ -102,15 +101,12 @@ if(arg._.length)
const useToken = await collect("DENO_DEPLOY_TOKEN", arg, env);
const useProject = await collect("DENO_DEPLOY_PROJECT", arg, env);
let scanProd:string[]|string|null = prompt(`Do you want to deploy to *production*?`);
let scanProd = confirm(`Do you want to deploy to *production*?`);
let argProd:string[] = [];
if(scanProd)
{
scanProd = prompt(`Are you sure? This will update the live project at "${useProject}"`);
scanProd = scanProd ? ["--prod"] : [];
}
else
{
scanProd = [];
scanProd = confirm(`Are you sure? This will update the live project at "${useProject}"`);
argProd = scanProd ? ["--prod"] : [];
}
const command = [
@ -124,13 +120,19 @@ if(arg._.length)
`--token=${useToken}`,
`--import-map=${imports.path}`,
`--exclude=.*,.*/,`,
...scanProd,
...argProd,
RootHost+"run.tsx"];
await SubProcess(command);
break;
}
case "baker" :
{
const args = ["run", `-A`, `--no-lock`, `--config=${config.path}`, RootHost+"run-baker.tsx", ...Deno.args];
await SubProcess(args);
break;
}
case "upgrade" :
{
await SubProcess(["install", `-A`, `-r`, `-f`, `--no-lock`, `--config=${config.path}`, RootHost+"cli.tsx", ...Deno.args]);

View File

@ -6,16 +6,17 @@
"@preact/signals": "https://esm.sh/@preact/signals@1.2.1",
"signals-original": "https://esm.sh/@preact/signals@1.2.1",
"@twind/core": "https://esm.sh/@twind/core@1.1.3",
">able/": "http://localhost:4507/",
">able/": "./",
">able/app.tsx": "./app.tsx"
},
"tasks": {
"check": "deno run -A --no-lock http://localhost:4507/cli.tsx check",
"local": "deno run -A --no-lock http://localhost:4507/cli.tsx local",
"debug": "deno run -A --no-lock http://localhost:4507/cli.tsx debug",
"serve": "deno run -A --no-lock http://localhost:4507/cli.tsx serve",
"cloud": "deno run -A --no-lock http://localhost:4507/cli.tsx cloud",
"install": "deno install -A -r -f -n able http://localhost:4507/cli.tsx"
"check": "deno run -A --no-lock ./cli.tsx check",
"local": "deno run -A --no-lock ./cli.tsx local",
"debug": "deno run -A --no-lock --inspect-wait=127.0.0.1:9229 ./cli.tsx debug",
"serve": "deno run -A --no-lock ./cli.tsx serve",
"cloud": "deno run -A --no-lock ./cli.tsx cloud",
"baker": "deno run -A --no-lock ./cli.tsx baker",
"install": "deno install -A -r -f -n able ./cli.tsx"
},
"compilerOptions": {
"jsx": "react-jsx",

View File

@ -1,20 +0,0 @@
{
"compilerOptions": { "lib": ["deno.window", "dom"],
"jsx": "react-jsx",
"jsxImportSource": "react"
},
"imports":
{
"react":"https://esm.sh/preact@10.15.1/compat",
"react/":"https://esm.sh/preact@10.15.1/compat/",
"react-original":"https://esm.sh/preact@10.15.1/compat",
},
"tasks":
{
"local": "deno run -A --reload=http://localhost:4507 --no-lock ./run-local.tsx --port=1234",
"serve": "deno run -A --reload=http://localhost:4507 --no-lock ./run-serve.tsx --port=1234",
"cloud": "deno run -A --reload=http://localhost:4507 --no-lock ./run-deploy.tsx",
"debug": "deno run -A --reload=http://localhost:4507 --no-lock --inspect-wait ./run-serve.tsx --port=1234",
}
}

View File

@ -1,3 +1,4 @@
//@able-types
import React from "react";
type MetasInputs = { [Property in MetaKeys]?: string };
@ -192,7 +193,7 @@ export const Router = {
React.useEffect(()=>{
history.replaceState({...routeGet, URL:undefined}, "", routeGet.URL);
window.addEventListener("popstate", ({state})=>
self.addEventListener("popstate", ({state})=>
{
dirtySet(true);
routeUpdate(state.Path, state.Params, state.Anchor);

View File

@ -1,3 +1,4 @@
//@able-types
import React from "react";
type StateArgs = {done?:boolean, open?:boolean};

111
run-baker.tsx Normal file
View File

@ -0,0 +1,111 @@
import { walk, type WalkOptions, ensureFile } from "https://deno.land/std@0.204.0/fs/mod.ts";
import ts, { isAssertEntry } from "npm:typescript";
const tsopts:ts.CompilerOptions = { declaration: true, emitDeclarationOnly: true };
const tshost = ts.createCompilerHost(tsopts);
const tstypes =(fileName: string):string=> {
let output = "";
tshost.writeFile = (fileName: string, contents: string) => output = contents;
ts.createProgram([fileName], tsopts, tshost).emit();
return output;
}
const tstypes_all =(fileNames: string[]):string[]=> {
const output:string[] = [];
tshost.writeFile = (fileName: string, contents: string) => output[fileName.indexOf(fileName)] = contents;
ts.createProgram(fileNames, tsopts, tshost).emit();
return output;
}
import * as SWCW from "https://esm.sh/@swc/wasm-web@1.3.62";
await SWCW.default();
const options:SWCW.Options = {
sourceMaps: false,
minify: true,
jsc:
{
target:"es2022",
minify:
{
compress: { unused: true },
mangle: false
},
parser:
{
syntax: "typescript",
tsx: true,
},
transform:
{
react: { runtime: "automatic" }
}
}
}
const dir = Deno.cwd();
const folder = dir.substring(dir.lastIndexOf("\\")+1);
console.log("searching", dir);
const extensions = ["tsx", "ts", "jsx", "js"];
try
{
await Deno.remove(".bake", { recursive: true });
console.log("rebuilding baked files");
}
catch(e)
{
console.log("fresh bake");
}
for await(const file of walk(dir, {includeDirs:false}))
{
const pathClean = file.path.replaceAll("\\", "/");
const pathRel = pathClean.substring(dir.length);
if(!pathRel.startsWith(".") && !pathRel.includes("/."))
{
const extension = file.name.substring(file.name.lastIndexOf(".")+1);
const pathBake = `.bake${pathRel}`;
if(extensions.includes(extension))
{
const pathDTS = pathBake.substring(0, pathBake.lastIndexOf("."))+".d.ts";
console.log("processing", pathRel);
const text = await Deno.readTextFile(pathClean);
const {code} = await SWCW.transform(text, { ...options, filename:file.name});
// check for types export directive
let tripleSlash = "";
const read = await Deno.open(file.path);
const buffer = new Uint8Array(256); // Set the buffer size to the maximum line length
try {
const bytesRead = await read.read(buffer);
if(bytesRead)
{
if(new TextDecoder().decode(buffer.subarray(0, bytesRead)).indexOf("@able-types") != -1)
{
tripleSlash =`/// <reference types=".${pathDTS.substring(pathDTS.lastIndexOf("/"))}" />\n`;
}
}
} finally {
read.close();
}
await ensureFile(pathBake);
await Deno.writeTextFile(pathBake, tripleSlash+code);
if(tripleSlash)
{
console.log("making types")
await ensureFile(pathDTS);
await Deno.writeTextFile(pathDTS, tstypes("."+pathRel));
}
}
else
{
await Deno.copyFile("."+pathRel, pathBake);
}
}
}

View File

@ -3,32 +3,10 @@ import * as TW from "@twind/core";
import TWPreTail from "https://esm.sh/v126/@twind/preset-tailwind@1.1.3/es2022/preset-tailwind.mjs";
import TWPreAuto from "https://esm.sh/v126/@twind/preset-autoprefix@1.0.7/es2022/preset-autoprefix.mjs";
const Configure =
{
theme: {},
presets: [TWPreTail(), TWPreAuto()],
hash: false
} as TW.TwindUserConfig;
export const Shadow =(inElement:HTMLElement, inConfig:TW.TwindUserConfig)=>
{
const ShadowDOM = inElement.attachShadow({ mode: "open" });
const ShadowDiv = document.createElement("div");
const ShadowCSS = document.createElement("style");
ShadowDOM.append(ShadowCSS);
ShadowDOM.append(ShadowDiv);
TW.observe(TW.twind(inConfig, TW.cssom(ShadowCSS)), ShadowDiv);
return ShadowDiv;
};
const Configure = { theme: {}, presets: [TWPreTail(), TWPreAuto()], hash: false} as TW.TwindUserConfig;
export default async(inSelector:string, inModulePath:string, inMemberApp="default", inMemberCSS="CSS", inShadow=false):Promise<(()=>void)|false>=>
{
if(!inModulePath)
{
return false;
}
let dom = document.querySelector(inSelector);
if(!dom)
{
@ -37,12 +15,18 @@ export default async(inSelector:string, inModulePath:string, inMemberApp="defaul
}
const module = await import(inModulePath);
const merge = inMemberCSS ? {...Configure, ...module[inMemberCSS]} : Configure;
if(inShadow)
{
dom = Shadow(dom as HTMLElement, merge);
const ShadowDOM = dom.attachShadow({ mode: "open" });
const ShadowDiv = document.createElement("div");
const ShadowCSS = document.createElement("style");
ShadowDOM.append(ShadowCSS);
ShadowDOM.append(ShadowDiv);
TW.observe(TW.twind(merge, TW.cssom(ShadowCSS)), ShadowDiv);
dom = ShadowDiv;
}
else
{

View File

@ -1,106 +0,0 @@
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";
const collect =async(inKey:string, inArg:Record<string, string>, inEnv:Record<string, string>):Promise<string|undefined>=>
{
const scanArg = inArg[inKey];
const scanEnvFile = inEnv[inKey];
const scanEnvDeno = Deno.env.get(inKey);
if(scanArg)
{
console.log(`Using "${inKey}" from passed argument.`);
return scanArg;
}
if(scanEnvFile)
{
console.log(`Using "${inKey}" from .env file.`);
return scanEnvFile;
}
if(scanEnvDeno)
{
console.log(`Using "${inKey}" from environment variable.`);
return scanEnvDeno;
}
const scanUser = await prompt(`No "${inKey}" found. Enter one here:`);
if(!scanUser || scanUser?.length < 3)
{
console.log("Exiting...");
Deno.exit();
}
return scanUser;
};
const prompt =async(question: string):Promise<string>=>
{
const buf = new Uint8Array(1024);
await Deno.stdout.write(new TextEncoder().encode(question));
const bytes = await Deno.stdin.read(buf);
if (bytes) {
return new TextDecoder().decode(buf.subarray(0, bytes)).trim();
}
throw new Error("Unexpected end of input");
};
try
{
console.log("Runing deploy!", Deno.mainModule);
let arg = parse(Deno.args);
let env = await Env.load();
let useToken = await collect("DENO_DEPLOY_TOKEN", arg, env);
let useProject = await collect("DENO_DEPLOY_PROJECT", arg, env);
let scanProd:string|string[] = await prompt(`Do you want to deploy to *production*? [y/n]`);
if(scanProd == "y")
{
scanProd = await prompt(`This will update the live project at ${useProject} are you sure you want to continue? [y/n]`);
scanProd = scanProd=="y" ? ["--prod"] : [];
}
else
{
scanProd = [];
}
const command = new Deno.Command(
`deno`,
{
args:[
"run",
"-A",
"--no-lock",
"https://deno.land/x/deploy/deployctl.ts",
"deploy",
`--project=${useProject}`,
`--import-map=./deno.json`,
`--token=${useToken}`,
...scanProd,
Deno.mainModule
],
stdin: "piped",
stdout: "piped"
}
);
const child = command.spawn();
// open a file and pipe the subprocess output to it.
const writableStream = new WritableStream({
write(chunk: Uint8Array): Promise<void> {
Deno.stdout.write(chunk);
return Promise.resolve();
},
});
child.stdout.pipeTo(writableStream);
// manually close stdin
child.stdin.close();
const status = await child.status;
}
catch(e)
{
console.error(e);
}

View File

@ -1,5 +1,5 @@
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 * as SWCW from "https://esm.sh/@swc/wasm-web@1.4.17";
import { HuntConfig } from "./checker.tsx";
import CustomServe from ">able/api.tsx";
@ -9,6 +9,12 @@ type DenoConfig = {imports:Record<string, string>};
const ImportMap:DenoConfig = {imports:{}};
let ImportMapProxies:Record<string, string> = {};
// (re)scan the project directory looking for the config
// process the found import map:
// - make a copy of the import map
// - change root relative imports that deno needs (starts with "./") to "/" for use in the browser
// - change
const ImportMapReload =async()=>
{
const [, {json, path}] = await HuntConfig();
@ -39,7 +45,6 @@ const ImportMapReload =async()=>
});
ImportMap.imports = Configuration.Remap(imports, Configuration);
}
else
{
@ -92,7 +97,7 @@ let Configuration:Configuration =
minify:
{
compress: { unused: true },
mangle: true
mangle: false
},
parser:
{
@ -162,6 +167,7 @@ export const Configure =(config:ConfigurationArgs)=>
}
let running = false;
export default async()=>
{
@ -185,6 +191,7 @@ export default async()=>
const headers = {"content-type":"application/json", "Access-Control-Allow-Origin": Configuration.Allow, "charset":"UTF-8"};
let proxy = Root + url.pathname;
// dont serve hidden files (end file or folder names with "__" to hide)
if(url.pathname.includes("__/") || url.pathname.lastIndexOf("__.") > -1)
{
return new Response(`{"error":"unmatched route", "path":"${url.pathname}"}`, {status:404, headers});
@ -193,20 +200,23 @@ export default async()=>
// proxy imports
if(url.pathname.startsWith(encodeURI("/>")))
{
console.log(ImportMapProxies);
console.log("checking for", url.pathname)
let bestMatch="";
for(let key in ImportMapProxies)
for(const key in ImportMapProxies)
{
if(url.pathname.startsWith(key) && key.length > bestMatch.length)
const match = url.pathname.startsWith(key) && key.length > bestMatch.length;
console.log(`key:${key} match:${match}`);
if(match)
{
bestMatch = key;
}
}
if(bestMatch.length)
{
const match = ImportMapProxies[bestMatch];
const value = ImportMapProxies[bestMatch];
const path = url.pathname.substring(bestMatch.length);
proxy = path ? match + path : Root + match;
proxy = path ? value + path : Root + value;
}
}

13
run.tsx
View File

@ -20,15 +20,8 @@ export default function(config:Serve.ConfigurationArgs)
}
}
if(isDeploy)
if(isDevelop)
{
import("./run-deploy.tsx");
}
else
{
if(isDevelop)
{
await import("./run-local.tsx");
}
Serve.default();
await import("./run-local.tsx");
}
Serve.default();