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/?q=function&page=515&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 20503 results for "function"(2191ms)

stevensDemohandleTelegramMessage.ts5 matches

@zhichuโ€ขUpdated 3 weeks ago
36 * Store a chat message in the database
37 */
38export async function storeChatMessage(
39 chatId,
40 senderId,
69 * Retrieve chat history for a specific chat
70 */
71export async function getChatHistory(chatId, limit = 50) {
72 try {
73 const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");
94 * Format chat history for Anthropic API
95 */
96function formatChatHistoryForAI(history) {
97 const messages = [];
98
118 * Analyze a Telegram message and extract memories from it
119 */
120async function analyzeMessageContent(
121 anthropic,
122 username,
499
500// Handle webhook requests
501export default async function (req: Request): Promise<Response> {
502 // Set webhook if it is not set yet
503 if (!isEndpointSet) {

stevensDemogetWeather.ts5 matches

@zhichuโ€ขUpdated 3 weeks ago
8const TABLE_NAME = `memories`;
9
10function summarizeWeather(weather: WeatherResponse) {
11 const summarizeDay = (day: WeatherResponse["weather"][number]) => ({
12 date: day.date,
25}
26
27async function generateConciseWeatherSummary(weatherDay) {
28 try {
29 // Get API key from environment
83}
84
85async function deleteExistingForecast(date: string) {
86 await sqlite.execute(
87 `
93}
94
95async function insertForecast(date: string, forecast: string) {
96 const { nanoid } = await import("https://esm.sh/nanoid@5.0.5");
97
112}
113
114export default async function getWeatherForecast(interval: number) {
115 const weather = await getWeather("Washington, DC");
116 console.log({ weather });

stevensDemogetCalendarEvents.ts6 matches

@zhichuโ€ขUpdated 3 weeks ago
6const LOCAL_TIMEZONE = "America/New_York";
7
8async function deleteExistingCalendarEvents() {
9 await sqlite.execute(
10 `
15}
16
17// Helper function to extract time from ISO string without timezone conversion
18function extractTimeFromISO(isoString) {
19 // Match the time portion of the ISO string
20 const timeMatch = isoString.match(/T(\d{2}):(\d{2}):/);
31}
32
33function formatEventToNaturalLanguage(event) {
34 const summary = event.summary || "Untitled event";
35
83}
84
85async function insertCalendarEvent(date, eventText) {
86 const { nanoid } = await import("https://esm.sh/nanoid@5.0.5");
87
97}
98
99export default async function getCalendarEvents() {
100 try {
101 const events = await getEvents(

stevensDemogenerateFunFacts.ts8 matches

@zhichuโ€ขUpdated 3 weeks ago
11 * @returns Array of previous fun facts
12 */
13async function getPreviousFunFacts() {
14 try {
15 const result = await sqlite.execute(
32 * @param dates Array of date strings in ISO format
33 */
34async function deleteExistingFunFacts(dates) {
35 try {
36 for (const date of dates) {
51 * @param factText The fun fact text
52 */
53async function insertFunFact(date, factText) {
54 try {
55 await sqlite.execute(
75 * @returns Array of generated fun facts
76 */
77async function generateFunFacts(previousFacts) {
78 try {
79 // Get API key from environment
197 * @returns Array of parsed facts
198 */
199function parseFallbackFacts(responseText, expectedDates) {
200 // Try to extract facts using regex
201 const factPattern = /(\d{4}-\d{2}-\d{2})["']?[,:]?\s*["']?(.*?)["']?[,}]/gs;
260
261/**
262 * Main function to generate and store fun facts for the next 7 days
263 */
264export async function generateAndStoreFunFacts() {
265 try {
266 // Get previous fun facts
301 * Intended to be used as a Val Town cron job
302 */
303export default async function() {
304 console.log("Running fun facts generation cron job...");
305 return await generateAndStoreFunFacts();

stevensDemo.cursorrules15 matches

@zhichuโ€ขUpdated 3 weeks ago
8### 1. Script Vals
9
10- Basic JavaScript/TypeScript functions
11- Can be imported by other vals
12- Example structure:
13
14```typescript
15export function myFunction() {
16 // Your code here
17}
25
26```typescript
27export default async function (req: Request) {
28 return new Response("Hello World");
29}
37
38```typescript
39export default async function () {
40 // Scheduled task code
41}
49
50```typescript
51export default async function (email: Email) {
52 // Process email
53}
57
58- Ask clarifying questions when requirements are ambiguous
59- Provide complete, functional solutions rather than skeleton implementations
60- Test your logic against edge cases before presenting the final solution
61- Ensure all code follows Val Town's specific platform requirements
70- **Never bake in secrets into the code** - always use environment variables
71- Include comments explaining complex logic (avoid commenting obvious operations)
72- Follow modern ES6+ conventions and functional programming practices if possible
73
74## Val Town Standard Libraries
75
76Val Town provides several hosted services and utility functions.
77
78### Blob Storage
124```
125
126## Val Town Utility Functions
127
128Val Town provides several utility functions to help with common project tasks.
129
130### Importing Utilities
176 {
177 name: "should add numbers correctly",
178 function: () => {
179 expect(1 + 1).toBe(2);
180 },
210โ”‚ โ”œโ”€โ”€ database/
211โ”‚ โ”‚ โ”œโ”€โ”€ migrations.ts # Schema definitions
212โ”‚ โ”‚ โ”œโ”€โ”€ queries.ts # DB query functions
213โ”‚ โ”‚ โ””โ”€โ”€ README.md
214โ”‚ โ”œโ”€โ”€ index.ts # Main entry point
226โ””โ”€โ”€ shared/
227 โ”œโ”€โ”€ README.md
228 โ””โ”€โ”€ utils.ts # Shared types and functions
229```
230
232- Hono is the recommended API framework (similar to Express, Flask, or Sinatra)
233- Main entry point should be `backend/index.ts`
234- **Static asset serving:** Use the utility functions to read and serve project files:
235 ```ts
236 // Use the serveFile utility to handle content types automatically
273- Run migrations on startup or comment out for performance
274- Change table names when modifying schemas rather than altering
275- Export clear query functions with proper TypeScript typing
276- Follow the queries and migrations pattern from the example
277

stevensDemocronDailyBrief.ts1 match

@zhichuโ€ขUpdated 3 weeks ago
1import { sendDailyBriefing } from "./sendDailyBrief.ts";
2
3export async function cronDailyBrief() {
4 try {
5 const chatId = Deno.env.get("TELEGRAM_CHAT_ID");

stevensDemoApp.tsx2 matches

@zhichuโ€ขUpdated 3 weeks ago
62};
63
64export function App() {
65 const [memories, setMemories] = useState<Memory[]>([]);
66 const [loading, setLoading] = useState(true);
139 const data = await response.json();
140
141 // Change the sorting function to show memories in chronological order
142 const sortedMemories = [...data].sort((a, b) => {
143 const dateA = a.createdDate || 0;

saucepointermain.tsx27 matches

@dcm31โ€ขUpdated 3 weeks ago
3import { createRoot } from "https://esm.sh/react-dom@18.2.0/client";
4
5function App() {
6 const [message, setMessage] = useState("Move around, hover, or click to see the sauce bottle change!");
7
65}
66
67function client() {
68 createRoot(document.getElementById("root")).render(<App />);
69
87 cursor.appendChild(clickableCursorImg);
88
89 // Cursor positioning function
90 function onMove(x, y) {
91 cursor.style.left = (x - 10) + 'px';
92 cursor.style.top = (y - 10) + 'px';
94
95 // Check if element is clickable
96 function isClickable(element) {
97 const clickableTags = ['A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA'];
98 return (
105
106 // Show clicking cursor
107 function showClickingCursor() {
108 defaultCursorImg.style.display = 'none';
109 clickableCursorImg.style.display = 'block';
114
115 // Show default or clickable cursor
116 function showDefaultOrClickableCursor(x, y) {
117 const target = document.elementFromPoint(x, y);
118 if (isClickable(target)) {
127
128 // Mouse event handlers
129 function onMouseMove(e) {
130 onMove(e.clientX, e.clientY);
131 showDefaultOrClickableCursor(e.clientX, e.clientY);
132 }
133
134 function onMouseDown(e) {
135 onMove(e.clientX, e.clientY);
136 showClickingCursor();
137 }
138
139 function onMouseUp(e) {
140 onMove(e.clientX, e.clientY);
141 showDefaultOrClickableCursor(e.clientX, e.clientY);
143
144 // Touch event handlers
145 function onTouchMove(e) {
146 if (e.touches.length > 0) {
147 const touch = e.touches[0];
151 }
152
153 function onTouchStart(e) {
154 if (e.touches.length > 0) {
155 const touch = e.touches[0];
159 }
160
161 function onTouchEnd(e) {
162 if (e.changedTouches.length > 0) {
163 const touch = e.changedTouches[0];
181}
182
183export default async function server(request: Request): Promise<Response> {
184 const url = new URL(request.url);
185
215
216// Standalone JS version for embedding on websites
217function getJavaScriptVersion() {
218 return `
219 (function() {
220 // Create cursor element
221 const cursor = document.createElement('div');
238 cursor.appendChild(clickableCursorImg);
239
240 // Cursor positioning function
241 function onMove(x, y) {
242 cursor.style.left = (x - 10) + 'px';
243 cursor.style.top = (y - 10) + 'px';
245
246 // Check if element is clickable
247 function isClickable(element) {
248 const clickableTags = ['A', 'BUTTON', 'INPUT', 'SELECT', 'TEXTAREA'];
249 return (
256
257 // Show clicking cursor
258 function showClickingCursor() {
259 defaultCursorImg.style.display = 'none';
260 clickableCursorImg.style.display = 'block';
265
266 // Show default or clickable cursor
267 function showDefaultOrClickableCursor(x, y) {
268 const target = document.elementFromPoint(x, y);
269 if (isClickable(target)) {
278
279 // Mouse event handlers
280 function onMouseMove(e) {
281 onMove(e.clientX, e.clientY);
282 showDefaultOrClickableCursor(e.clientX, e.clientY);
283 }
284
285 function onMouseDown(e) {
286 onMove(e.clientX, e.clientY);
287 showClickingCursor();
288 }
289
290 function onMouseUp(e) {
291 onMove(e.clientX, e.clientY);
292 showDefaultOrClickableCursor(e.clientX, e.clientY);
294
295 // Touch event handlers
296 function onTouchMove(e) {
297 if (e.touches.length > 0) {
298 const touch = e.touches[0];
302 }
303
304 function onTouchStart(e) {
305 if (e.touches.length > 0) {
306 const touch = e.touches[0];
310 }
311
312 function onTouchEnd(e) {
313 if (e.changedTouches.length > 0) {
314 const touch = e.changedTouches[0];

FileDumpThingupload.ts2 matches

@wolfโ€ขUpdated 3 weeks ago
5const API_URL = `https://filedumpthing.val.run/api/upload`;
6
7async function main() {
8 try {
9 // Get filename from args or use a temporary name (will be replaced with appropriate extension)
71}
72
73// Run the main function only once
74if (import.meta.main) {
75 main();

FileDumpThingutils.ts1 match

@wolfโ€ขUpdated 3 weeks ago
13 * Simple and reliable approach to detect binary files
14 */
15export function isTextContent(buffer: Uint8Array): boolean {
16 // Convert buffer to string and check for null bytes
17 const str = new TextDecoder().decode(buffer);

getFileEmail4 file matches

@shouserโ€ขUpdated 3 weeks ago
A helper function to build a file's email
tuna

tuna8 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.