diff --git a/cc-tweaked/host.ts b/cc-tweaked/host.ts index 50dad33..18e659e 100755 --- a/cc-tweaked/host.ts +++ b/cc-tweaked/host.ts @@ -1,32 +1,29 @@ #!/bin/env -S deno run --allow-read --allow-net async function main() { - const [program_path] = Deno.args; - if (program_path === undefined) fail_with("Usage: host.ts "); const port = 1728; - const server = Deno.serve({ port }, () => handle(program_path)); + const server = Deno.serve({ port }, (request) => handle(request)); await server.finished; } -async function handle(program_path: string) { - console.log("Serving", program_path); - const file = await try_else( - () => Deno.open(program_path, { read: true }), - () => fail_with("Program at", program_path, "does not exists"), - ); - return new Response(file.readable); +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); } -function fail_with(...message: string[]) { - console.error(...message); - return Deno.exit(1); -} - -async function try_else(operation: () => T | Promise, on_error: (error: unknown) => T | Promise) { +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 { - return await operation(); - } catch (error) { - return await on_error(error); + 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 }); } }