untitled-1482main.ts1 match
1516// // Learn more: https://docs.val.town/vals/http/
17// export default async function (req: Request): Promise<Response> {
18// return app.fetch(req);
19// }
101const BookSchema = z.enum(BIBLE_BOOKS);
102103// Function to convert book names to API format
104function normalizeBookName(bookName: string): string {
105// Simple mapping for common books - the API uses standard abbreviations
106const bookMap: { [key: string]: string } = {
45- Ask clarifying questions when requirements are ambiguous
6- Provide complete, functional solutions rather than skeleton implementations
7- Test your logic against edge cases before presenting the final solution
8- Ensure all code follows Val Town's specific platform requirements
17- **Never bake in secrets into the code** - always use environment variables
18- Include comments explaining complex logic (avoid commenting obvious operations)
19- Follow modern ES6+ conventions and functional programming practices if possible
2021## Types of triggers
2829```ts
30export default async function (req: Request) {
31return new Response("Hello World");
32}
4243```ts
44export default async function () {
45// Scheduled task code
46}
5657```ts
58export default async function (email: Email) {
59// Process email
60}
66## Val Town Standard Libraries
6768Val Town provides several hosted services and utility functions.
6970### Blob Storage
120```
121122## Val Town Utility Functions
123124Val Town provides several utility functions to help with common project tasks.
125126### Importing Utilities
200โ โโโ database/
201โ โ โโโ migrations.ts # Schema definitions
202โ โ โโโ queries.ts # DB query functions
203โ โ โโโ README.md
204โ โโโ routes/ # Route modules
219โโโ shared/
220โโโ README.md
221โโโ utils.ts # Shared types and functions
222```
223226- Hono is the recommended API framework
227- Main entry point should be `backend/index.ts`
228- **Static asset serving:** Use the utility functions to read and serve project files:
229```ts
230import { readFile, serveFile } from "https://esm.town/v/std/utils@85-main/index.ts";
260- Run migrations on startup or comment out for performance
261- Change table names when modifying schemas rather than altering
262- Export clear query functions with proper TypeScript typing
263264## Common Gotchas and Solutions
hello-realtimeutils.ts3 matches
67// Builds the URL for a Realtime API endpoint.
8export function makeUrl(callId?: string, action?: string) {
9let url = REALTIME_BASE_URL;
10if (!callId) {
2223// Builds the headers for a Realtime API endpoint.
24export function makeHeaders(contentType?: string) {
25const obj: Record<string, string> = {
26Authorization: `Bearer ${OPENAI_API_KEY}`,
3132// Debug helper for printing Realtime API errors.
33export async function getErrorText(resp: Response) {
34const errBody = await resp.text().catch(() => "<no body>");
35return `${resp.status} ${resp.statusText}: ${errBody}`;
hello-realtimeobserver.ts1 match
48}
49switch (message.type) {
50case "response.function_call_arguments.done":
51this.handler.onTool(message.name, message.arguments);
52break;
hello-realtimeindex.html5 matches
193let callStartTime = null;
194195function formatTimestamp() {
196if (!callStartTime) {
197return "00:00.000";
208}
209210function log(...args) {
211const timestamp = formatTimestamp();
212const message = args.map(
224}
225226function setStatus(status, ledState = "disconnected") {
227statusTextEl.textContent = status;
228statusLedEl.className = `status-led ${ledState}`;
243}
244245async function start() {
246if (pc) {
247// If already connected, this is a stop action
348}
349350async function stop() {
351log("Stopping voice agent connection");
352setStatus("Disconnecting...", "connecting");
hello-realtimeagent.ts5 matches
11apologize and say you can't help with that.
12When the user says goodbye or you think the call is over, say a brief goodbye and then
13invoke the end_call function.
14---
15Short summary:
34const VOICE = "marin";
35const HANGUP_TOOL = {
36type: "function",
37name: "end_call",
38description: `
39Use this function to hang up the call when the user says goodbye
40or otherwise indicates they are about to end the call.`,
41};
4243// Builds the declarative session configuration for a Realtime API session.
44export function makeSession() {
45return {
46type: "realtime",
104105// Creates the runtime handler for the session.
106export function createHandler(client: ObserverClient, callId: string) {
107return new AgentHandler(client, callId);
108}
10import { formatDateRelative, formatNumber, PaddedSpinner, Button } from './ui.tsx'
1112export function Post({ cast, display = 'default', hideSeparator = false }) {
13const navigate = useNavigate()
1448}
4950function PostMedia({ cast }) {
51const images = cast.embeds?.filter((embed) => !!embed?.metadata?.image)
52const videos = cast.embeds?.filter((embed) => !!embed?.metadata?.video)
105}
106107function PostEmbeds({ cast }) {
108const frames = cast.embeds?.filter((embed) => !!embed?.metadata?.frame)
109const urls = cast.embeds?.filter((embed) => !!embed?.metadata?.html && !embed?.metadata?.frame)
144}
145146function PostPostedFrom({ cast, display = 'default' }) {
147if (display != 'expanded') return null
148if (!cast) return null
151}
152153function PostInteractions({ cast, display = 'default' }) {
154const hideInteractions = ['quote', 'sub-comment', 'preview'].includes(display)
155if (!cast || hideInteractions) return null
179}
180181export function Feed({
182queryKey,
183queryFn,
221}
222223function FeedItems({ feed, display, renderItem = undefined, containerClass = 'flex flex-col' }) {
224if (renderItem) {
225return <div className={containerClass}>{feed?.map((item) => renderItem(item))}</div>
245}
246247export function SmallMediaPost({ cast }) {
248const navigate = useNavigate()
249const [isFullscreen, setIsFullscreen] = useState(false)
SonarMiniAppsScreen.tsx3 matches
8import { Feed } from '../components/Post.tsx'
910export function MiniAppsScreen() {
11return (
12<div>
22}
2324function MiniAppsList() {
25return (
26<Feed
33}
3435function MiniApp({ miniapp }) {
36const { fcsdk, context } = useFarcasterMiniApp()
37
4import { NavLink, Outlet } from 'https://esm.sh/react-router@7'
56export function Section({ children, ...props }: any) {
7const sectionClass = `p-5 rounded-3xl bg-neutral-400/15 ${props.className || ''}`
8return (
98}
99100// export function Input(props: any) {
101// const inputClass = "dark:bg-white dark:text-black bg-black text-white rounded-md px-3 py-1 ";
102// return <input class={inputClass} {...props} />;
103// }
104105// export function Button(props: any) {
106// const buttonClass = "dark:bg-white dark:text-black bg-black text-white rounded-md px-3 py-1 ";
107// return <button class={buttonClass} {...props} />;
108// }
109110export function Sheet({ children, showSheet, setShowSheet }: any) {
111return (
112<>
125}
126127export function MonoButton(props: any) {
128return (
129<Button {...props}>
133}
134135export function MonoButtonWithStatus(props: any) {
136const [status, setStatus] = useState<any>()
137const handleClick = async () => {
154}
155156export function Separator({ className = '' }) {
157return <div className={`border-b border-neutral-400/25 ${className}`}></div>
158}
159160export function PaddedSpinner() {
161return (
162<div className="flex flex-row items-center justify-center p-4 opacity-50 h-32">
166}
167168export function PaddedError({ message }) {
169return (
170<div className="flex flex-row items-center justify-center p-4 opacity-50 h-32">
174}
175176export function StatsRows({ stats }) {
177return (
178<div className="flex flex-col ">
190}
191192export function Debug({ title, data, className = '' }) {
193return (
194<div className={className}>
199}
200201export function NavTabs({ navLinks }) {
202return (
203<>
222}
223224export function NavOutlet({ navLinks }) {
225return (
226<>
235//////////
236237export function formatJSON(json: any) {
238return JSON.stringify(json, null, 2)
239}
263}
264265export function BackButton() {
266return <ArrowLeft className="w-5 h-5 m-2 cursor-pointer opacity-50" onClick={() => (window.location.href = '/')} />
267}
268269export function ShareButton({ onClick }) {
270return <Share className="w-5 h-5 m-2 cursor-pointer opacity-50" onClick={onClick} />
271}