import { fetch } from "https://esm.town/v/std/fetch";
export function sunbeamValTownFn(valtownToken: string) {
return async (req: Request) => {
const { Hono } = await import("npm:hono");
const app = new Hono();
app.get("/", async (c) => {
const resp = await fetch("https://api.val.town/v1/me", {
headers: {
Authorization: `Bearer ${valtownToken}`,
},
});
const { id: userID } = await resp.json();
return c.json({
title: "Val Town",
commands: [
{
name: "search-vals",
title: "Seach Vals",
mode: "view",
params: [
{
name: "user",
type: "string",
description: "User ID",
default: userID,
},
],
},
{
name: "view-val",
title: "view-val",
mode: "view",
params: [
{
name: "val",
type: "string",
description: "Val ID",
required: true,
},
],
},
],
});
});
app.post("/search-vals", async (c) => {
const { params, query } = await c.req.json();
const { user } = params;
const endpoint = query
? `https://api.val.town/v1/search/vals?query=${
encodeURIComponent(query)
}`
: `https://api.val.town/v1/users/${user}/vals`;
const resp = await fetch(endpoint, {
headers: {
Authorization: `Bearer ${valtownToken}`,
},
});
const { data: vals } = await resp.json();
return c.json({
type: "list",
dynamic: true,
items: vals.map((val) => {
const fullName = `${val.author.username}.${val.name}`;
return {
title: fullName,
accessories: [val.privacy],
actions: [
{
title: "View Val",
onAction: {
type: "run",
command: "view-val",
params: {
val: val.id,
},
},
},
{
title: "Open Val",
key: "o",
onAction: {
type: "open",
exit: true,
target: `https://val.town/v/${fullName}`,
},
},
],
};
}),
});
});
app.post("/view-val", async (c) => {
const { params } = await c.req.json();
const resp = await fetch(`https://api.val.town/v1/vals/${params.val}`, {
headers: {
Authorization: `Bearer ${valtownToken}`,