Val Town Code SearchReturn to Val Town

API Access

You can access search results via JSON API by adding format=json to your query:

https://codesearch.val.run/image-url.jpg%20%22Image%20title%22?q=function&page=53&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=function

Returns an array of strings in format "username" or "username/projectName"

Found 32873 results for "function"(7179ms)

birdfactstest.ts1 match

@greasegum•Updated 4 days ago
2const API_URL = "https://greasegum--47620ec654ae11f088f8f69ea79377d9.web.val.run";
3
4async function testAPI() {
5 console.log("Testing Bird Facts API...");
6

strivemain.tsx16 matches

@join•Updated 4 days ago
57// --- DATABASE MIGRATION & INITIALIZATION ---
58
59async function initializeDatabase() {
60 if (Deno.env.get(DB_INIT_KEY) === "true") return;
61 if (Deno.env.get("DB_INITIALIZING") === "true") {
87}
88
89// --- UTILITY & HELPER FUNCTIONS ---
90
91async function hashToken(token: string) {
92 const data = new TextEncoder().encode(token);
93 const hash = await crypto.subtle.digest("SHA-256", data);
95}
96
97function extractJson(str: string): any {
98 const match = str.match(/\{.*\}/s);
99 if (!match) throw new Error("AI response did not contain a valid JSON object.");
106}
107
108function jsonResponse(data: any, status = 200) {
109 const headers = { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*" };
110 return new Response(JSON.stringify(data), { status, headers });
111}
112
113function optionsResponse() {
114 return new Response(null, {
115 status: 204,
122}
123
124async function verifyAuth(req: Request): Promise<string | null> {
125 const authHeader = req.headers.get("Authorization");
126 if (!authHeader || !authHeader.startsWith("Bearer ")) return null;
132
133// --- HTML & FRONTEND (SPA) ---
134function generateHtml(sourceUrl: string) {
135 // This is a complete, functional SPA.
136 return `<!DOCTYPE html>
137<html lang="en">
156 </main>
157 <script>
158 (function() {
159 const apiUrl = '${sourceUrl}api';
160 const app = document.getElementById('app-container');
163
164 // --- API CLIENT ---
165 async function resilientFetch(path, options = {}) {
166 options.headers = { ...options.headers, 'Content-Type': 'application/json' };
167 if (state.token) options.headers['Authorization'] = \`Bearer \${state.token}\`;
183
184 // --- UI RENDERING ---
185 function renderNav() {
186 if (state.token) {
187 nav.innerHTML = \`<a href="#/feed">Feed</a> | <a href="#/my-habits">My Habits</a> | <a href="#" id="logout-btn">Logout</a>\`;
191 }
192
193 function renderLoginView() {
194 app.innerHTML = \`<div id="login-view" class="view active"><h2>Login</h2>...</div>\`;
195 // Add form and event listener for login
196 }
197 // Add render functions for all other views (register, feed, habits, etc.)
198
199 // --- ROUTING ---
200 function router() {
201 const path = window.location.hash.slice(1) || '/';
202 renderNav();
232// --- MAIN HTTP VAL HANDLER ---
233
234export default async function handleRequest(req: Request): Promise<Response> {
235 await initializeDatabase();
236 const url = new URL(req.url);

socraticmain.tsx9 matches

@join•Updated 4 days ago
71/**
72 * Ensures the database is initialized and migrated to the latest schema version.
73 * This function is designed to be idempotent and safe for concurrent execution.
74 * It uses a simple locking mechanism via Deno.env to prevent race conditions
75 * during the first-ever initialization in a serverless environment.
76 */
77async function initializeDatabase() {
78 if (Deno.env.get(DB_INIT_KEY) === "true") {
79 return;
127// --- HTML & FRONTEND ---
128
129function generateHtml(sourceUrl: string, affirmations: string[]) {
130 return `<!DOCTYPE html>
131<html lang="en">
339
340<script>
341(function() {
342 const API_URL = '${sourceUrl}';
343 const affirmations = ${JSON.stringify(affirmations)};
359 let affirmationInterval;
360
361 function showLoading(visible) {
362 if (visible) {
363 let currentAffirmation = 0;
386 * @param {number} backoff - The initial backoff in milliseconds.
387 */
388 async function resilientFetch(url, options, retries = 3, backoff = 300) {
389 for (let i = 0; i < retries; i++) {
390 try {
403 }
404
405 function renderResponse(entryText, guidance) {
406 $$.initialView.classList.add("hidden");
407 $$.responseArea.classList.remove("hidden");
465 * @throws {Error} If no valid JSON object is found.
466 */
467function extractJson(str) {
468 const match = str.match(/\{.*\}/s);
469 if (!match) {
543
544// Main request handler for serving the HTML application.
545export default async function(req: Request) {
546 const url = new URL(req.url);
547

feedburnermain.tsx5 matches

@wizos•Updated 4 days ago
1async function handler(req) {
2 var _a;
3 const origin = req.headers.get("Origin");
94 }
95}
96function processURLsInDoc(doc, targetURL, attrs) {
97 const targetHostname = targetURL.hostname;
98 attrs.forEach((attr) => {
140 "https://",
141];
142function processURL(url, targetURL) {
143 if (!SUPPORTED_PROTOCOLS.some((prefix) => url.startsWith(prefix))) {
144 return url;
158 }
159}
160function processURLsInContent(content, targetURL) {
161 const urlCache = /* @__PURE__ */ new Map();
162 const processURLWithCache = (url) => {
171 });
172}
173function setCORSHeaders(responseHeaders, origin) {
174 responseHeaders.set("Access-Control-Allow-Origin", origin ?? "*");
175 responseHeaders.set("access-control-allow-methods", "GET,POST,PUT,PATCH,TRACE,DELETE,HEAD,OPTIONS");

myNewWebsiteApp.tsx1 match

@derekbrimley•Updated 4 days ago
2import { useState } from "https://esm.sh/react@18.2.0";
3
4export function App() {
5 const [clicked, setClicked] = useState(0);
6 return (

stevensDemotestDailyBrief.ts1 match

@derekbrimley•Updated 4 days ago
4import { DateTime } from "https://esm.sh/luxon@3.4.4";
5
6export async function testDailyBrief() {
7 try {
8 const testChatId = Deno.env.get("TEST_TELEGRAM_CHAT_ID");

stevensDemosetupTelegramChatDb.ts1 match

@derekbrimley•Updated 4 days ago
2// Run this script manually to create the database table
3
4export default async function setupTelegramChatDb() {
5 try {
6 // Import SQLite module

stevensDemosendDailyBrief.ts6 matches

@derekbrimley•Updated 4 days ago
13} from "../memoryUtils.ts";
14
15async function generateBriefingContent(anthropic, memories, today, isSunday) {
16 try {
17 const weekdaysHelp = generateWeekDays(today);
96}
97
98export async function sendDailyBriefing(chatId?: string, today?: DateTime) {
99 // Get API keys from environment
100 const apiKey = Deno.env.get("ANTHROPIC_API_KEY");
135 const lastSunday = today.startOf("week").minus({ days: 1 });
136
137 // Fetch relevant memories using the utility function
138 const memories = await getRelevantMemories();
139
216}
217
218function generateWeekDays(today) {
219 let output = [];
220
239// console.log(weekDays);
240
241// Export a function that calls sendDailyBriefing with no parameters
242// This maintains backward compatibility with existing cron jobs
243export default async function (overrideToday?: DateTime) {
244 return await sendDailyBriefing(undefined, overrideToday);
245}

stevensDemoREADME.md2 matches

@derekbrimley•Updated 4 days ago
16In a normal server environment, you would likely use a middleware [like this one](https://hono.dev/docs/getting-started/nodejs#serve-static-files) to serve static files. Some frameworks or deployment platforms automatically make any content inside a `public/` folder public.
17
18However in Val Town you need to handle this yourself, and it can be suprisingly difficult to read and serve files in a Val Town Project. This template uses helper functions from [stevekrouse/utils/serve-public](https://www.val.town/x/stevekrouse/utils/branch/main/code/serve-public/README.md), which handle reading project files in a way that will work across branches and forks, automatically transpiles typescript to javascript, and assigns content-types based on the file's extension.
19
20### `index.html`
26## CRUD API Routes
27
28This app has two CRUD API routes: for reading and inserting into the messages table. They both speak JSON, which is standard. They import their functions from `/backend/database/queries.ts`. These routes are called from the React app to refresh and update data.
29
30## Errors

stevensDemoREADME.md2 matches

@derekbrimley•Updated 4 days ago
4
5* `migrations.ts` - code to set up the database tables the app needs
6* `queries.ts` - functions to run queries against those tables, which are imported and used in the main Hono server in `/backend/index.ts`
7
8## Migrations
18The queries file is where running the migrations happen in this app. It'd also be reasonable for that to happen in index.ts, or as is said above, for that line to be commented out, and only run when actual changes are made to your database schema.
19
20The queries file exports functions to get and write data. It relies on shared types and data imported from the `/shared` directory.

discordWebhook2 file matches

@stevekrouse•Updated 16 hours ago
Helper function to send Discord messages
tuna

tuna9 file matches

@jxnblk•Updated 3 weeks ago
Simple functional CSS library for Val Town
lost1991
import { OpenAI } from "https://esm.town/v/std/openai"; export default async function(req: Request): Promise<Response> { if (req.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "*",
webup
LangChain (https://langchain.com) Ambassador, KubeSphere (https://kubesphere.io) Ambassador, CNCF OpenFunction (https://openfunction.dev) TOC Member.