Public
Script
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
export class Cli {
constructor(public author: string) {}
fetch = async (req: Request) => {
const url = new URL(req.url);
const [name, ...args] = url.pathname.slice(1).split("/");
if (!name) {
return new Response("Not Found", { status: 404 });
}
const esmUrl = `https://esm.town/v/${this.author}/${name}`;
const { output, code } = await this.run(esmUrl, { args });
if (code !== 0) {
return new Response(output, { status: 500 });
}
return new Response(output, { status: 200 });
};
run = async (url: string, options: {
args: string[];
}) => {
const { default: runFn } = await import(url);
if (typeof runFn !== "function") {
throw new Error("Val should have a default export that is a function");
}
const logs: string[] = [];
globalThis.console = new Proxy(console, {
get(target, key) {
const real = target[key];
if (typeof real === "function" && typeof key === "string") {
const fn = function(...args: any[]) {
logs.push(args.join(" "));
return real.call(this, ...args);
};
return fn;
}
},
});
try {
await runFn(options.args);
return { output: logs.join("\n"), code: 0 };
} catch (err) {
return { output: logs.join("\n"), code: 1 };
}
};
}
export function createCli(author: string) {
return new Cli(author);
}
September 1, 2024