Back

Version 10

10/11/2024
export default async function(req: Request): Promise<Response> {
let json = await req.json();
const { val, args } = json;
const mod = await import(`https://esm.town/v/` + val);
const resp = getMainExport(mod);

if (!resp.ok) {
return Response.json({ error: { message: resp.error.message, name: resp.error.name, stack: resp.error.stack } }, {
status: 500,
});
}
if (typeof resp.value !== "function") {
return Response.json({
error: { message: "The first export of this val is not a function and cannot be run with args" },
}, {});
}

return Response.json(await resp.value(...args));
}

function getMainExport(
mod: any,
): { ok: true; value: any } | { ok: false; error: Error } {
if ("default" in mod) {
return { ok: true, value: mod.default };
}

const exports = Object.keys(mod);

if (exports.length > 1) {
const error = new Error(
`Vals require a default export, or exactly one named export. This val exports: ${exports.join(", ")}`,
);
error.name = "ImportValError";
return { ok: false, error };
} else if (exports.length === 0) {
maxm-pretendingtoberun.web.val.run
Updated: October 11, 2024