big update

This commit is contained in:
2026-01-01 21:27:58 -05:00
parent a1b7382288
commit 933d47c150
27 changed files with 184 additions and 73 deletions

76
main.ts
View File

@@ -1,27 +1,22 @@
import path from "node:path";
import { walk } from "@std/fs/walk";
import "@std/dotenv/load";
import { contentType } from "@std/media-types";
const NET_PORT = 4536;
const NET_HOST = '127.0.0.1';
const WEB_ROOT = './res/';
const _PORT = Deno.env.get('NET_PORT');
if (!_PORT || isNaN(parseInt(_PORT))) throw new Error("No NET_PORT specified in env");
const NET_PORT = parseInt(_PORT);
interface FileMapping {
endpoints: string[],
path: string,
mime: string
}
const NET_HOST = Deno.env.get('NET_HOST');
if (!NET_HOST) throw new Error("No NET_HOST specified in env");
const mappings: FileMapping[] = [
{
endpoints: ['/', '/index.html'],
path: "/index.html",
mime: "text/html"
},
{
endpoints: ['/style.css'],
path: "/style.css",
mime: "text/css"
}
] as const;
const WEB_ROOT = Deno.env.get('WEB_ROOT');
if (!WEB_ROOT) throw new Error("No WEB_ROOT specified in env");
const DIR_ROOT = path.join(Deno.cwd(), WEB_ROOT);
const FILES = (await Array.fromAsync(walk(DIR_ROOT))).filter(entry => entry.isFile).map(entry => entry.path.replaceAll(Deno.cwd(), '').replaceAll('\\', '/'));
console.log(FILES)
Deno.serve({
hostname: NET_HOST,
@@ -34,21 +29,34 @@ Deno.serve({
headers: { "Content-Type": "text/plain" }
});
const url = new URL(req.url);
try {
const url = new URL(req.url);
if (url.pathname == '/') url.pathname = '/index.html';
if (req.headers.get('user-agent')?.includes("Mobile") && url.pathname == '/') url.pathname = '/mobile.html';
else if (url.pathname == '/') url.pathname = '/index.html';
const mapping = mappings.find(val => val.endpoints.some(val => url.pathname === val));
const match = FILES.find(file => file.replace(WEB_ROOT, '') == url.pathname);
console.log(`${addr.remoteAddr.hostname}:${addr.remoteAddr.port} ${req.method} ${url.pathname} | mapping exists: ${typeof mapping !== 'undefined'}`);
return new Promise<Response>(resolve => {
if (mapping) {
Deno.readFile(path.join(WEB_ROOT, mapping.path)).then(data => {
resolve(new Response(data, { headers: { "Content-Type": mapping.mime }}));
}).catch(reason => {
console.error(reason);
resolve(notFound);
});
} else resolve(notFound);
});
console.log(`${addr.remoteAddr.hostname}:${addr.remoteAddr.port} ${req.method} ${url.pathname} | mapping exists: ${typeof match !== 'undefined'}`);
return new Promise<Response>(resolve => {
if (match) {
Deno.readFile(path.join(Deno.cwd(), match)).then(data => {
const headers = new Headers();
const last = match.split('/').at(-1);
if (last) {
const mime = contentType(last.substring(last.indexOf('.')));
if (mime) headers.set("Content-Type", mime);
}
resolve(new Response(data, { headers }));
}).catch(reason => {
console.error(reason);
resolve(notFound);
});
} else resolve(notFound);
});
} catch {
return notFound;
}
});