import { eval_ } from "https://esm.town/v/stevekrouse/eval_";
import { fetchPost as fetchBskyPost } from "https://esm.town/v/vladimyr/fetchBlueskyPost";
import { fetchTweet } from "https://esm.town/v/vladimyr/fetchTweet";
export default async function(req: Request): Promise<Response> {
const reqURL = new URL(req.url);
const query = reqURL.pathname.slice(1);
if (query.startsWith("https://")) {
const pathname = query.replace(/^https:\/\//, "/");
const redirectURL = new URL(pathname, reqURL);
return Response.redirect(redirectURL);
}
let post, code, result;
try {
post = await fetchPost(`https://${query}`);
result = await postEval(post, [req]);
return result;
} catch (e) {
return Response.json({ code, post, result }, { status: 500 });
}
}
export async function postEval(post, args?) {
const code = post.text.split("```")[1]
.trim()
.replaceAll(/</g, "<")
.replaceAll(/>/g, ">")
.replaceAll(/&/g, "&");
return eval_(code, args);
}
export async function fetchPost(url: string | URL) {
const postURL = new URL(url);
if (["x.com", "twitter.com"].includes(postURL.hostname)) {
const tweet = await fetchTweet(postURL.href);
return { text: tweet.text };
}
if (postURL.hostname === "bsky.app") {
const bskyPost = await fetchBskyPost(postURL);
return { text: bskyPost.record.text };
}
throw new TypeError("Invalid post URL");
}