bundler/server.ts

57 lines
1.5 KiB
TypeScript
Raw Normal View History

2020-05-13 16:00:14 +00:00
#!/usr/bin/env -S deno run --allow-run --allow-net
2020-05-13 14:39:34 +00:00
// Automated bundle server
import { bool } from "https://code.thunderk.net/typescript/functional/raw/1.0.0/all.ts";
2020-05-14 09:24:38 +00:00
import {
Response,
serve,
ServerRequest,
2020-12-02 21:06:45 +00:00
} from "https://deno.land/std@0.79.0/http/server.ts";
2020-05-13 14:39:34 +00:00
2020-05-14 09:24:38 +00:00
export async function processRequest(
req: ServerRequest,
runner = Deno.run,
): Promise<Response> {
const params = req.url.split("/").filter(bool);
const lib = params[0] || "all";
const version = params[1] || "master";
const file = params.length > 2 ? params.slice(2).join("/") : "all";
const path =
`https://code.thunderk.net/typescript/${lib}/raw/${version}/${file}.ts`;
2020-05-14 09:29:24 +00:00
if (!path.match(/^[a-z0-9\/\.\-:_]+$/)) {
2020-05-14 09:24:38 +00:00
return {
status: 400,
body: `console.error("bundler error - Invalid path ${path}");`,
};
}
const process = runner({
cmd: ["deno", "bundle", path],
stdout: "piped",
});
const output = await process.output();
const status = await process.status();
if (status.success) {
return { body: output };
} else {
return {
status: 500,
body: `console.error("bundler error - Failed to bundle ${path}");`,
};
}
}
export async function serveBundles() {
2020-05-13 16:00:14 +00:00
const listen = { hostname: "0.0.0.0", port: 8000 };
const server = serve(listen);
console.log(`Serving bundles on ${listen.hostname}:${listen.port} ...`);
for await (const req of server) {
2020-05-14 09:24:38 +00:00
const response = await processRequest(req);
await req.respond(response);
2020-05-13 14:39:34 +00:00
}
}
2020-05-13 16:00:14 +00:00
2020-05-14 09:24:38 +00:00
if (import.meta.main) {
await serveBundles();
}