mc-computer-scripts/cc-tweaked/host.ts

30 lines
983 B
TypeScript
Executable file

#!/bin/env -S deno run --allow-read --allow-net
async function main() {
const port = 1728;
const server = Deno.serve({ port }, (request) => handle(request));
await server.finished;
}
async function handle(request: Request) {
const script = await open_requested_script(request);
if (script instanceof Response) return script;
console.log("Serving", script.path);
return new Response(script.content.readable);
}
async function open_requested_script(request: Request) {
const requested_path = new URL(request.url).pathname.slice(1);
const invalid = () => new Response("Invalid script.", { status: 400 });
if (requested_path.includes("/")) return invalid();
if (requested_path.includes(".")) return invalid();
try {
const path = "./scripts/" + requested_path + ".lua";
const content = await Deno.open(path, { read: true });
return { path, content };
} catch (_) {
return new Response("Unknown script.", { status: 400 });
}
}
if (import.meta.main) await main();