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/%22$%7Burl%7D/%22https:/esm.town/v/std/catch//%22?q=function&page=1&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 40689 results for "function"(1861ms)

tinycanvasmain.ts2 matches

@zarutianโ€ขUpdated 47 mins ago
13
14*/
15const handler = async function(req) {
16 const req_url = new URL(req.url);
17 if (req_url.pathname == "/") {
79 `, { status: 404, statusText: "Not found.", headers: { "Content-Type": "text/html", }})
80}
81export default async function (req: Request): Promise<Response> {
82 try {
83 return await handler(req);

Notesmain.tsx18 matches

@jsonโ€ขUpdated 49 mins ago
1export default function () {
2 const body = `<!doctype html>
3<html lang="en">
96
97 /************************************************************************
98 * State: raw variables & functions, and evaluated variables
99 ************************************************************************/
100 const rawVars = new Map(); // name -> rhs string (raw)
101 const functions = new Map(); // name -> { params: [], body: "..." }
102 const computedVars = new Map(); // name -> evaluated value (primitive, array, string, etc)
103
105 * Helpers
106 ************************************************************************/
107 function isQuotedString(s) {
108 return (s.length >= 2) && ((s[0] === '"' && s[s.length-1] === '"') || (s[0] === "'" && s[s.length-1] === "'"));
109 }
110
111 function toObj(map) {
112 const o = Object.create(null);
113 for (const [k,v] of map.entries()) o[k] = v;
117 // Evaluate an expression string in a sandbox that includes:
118 // - current computedVars
119 // - user functions (as JS functions that evaluate their bodies with the same sandbox + parameters)
120 // - builtins
121 function evalWithScope(expr) {
122 // Build base scope
123 const scope = Object.assign({}, builtins, toObj(computedVars));
124 // attach user functions into scope as callables
125 for (const [name, def] of functions.entries()) {
126 scope[name] = (...args) => {
127 // local scope that includes current computedVars and builtins, plus params
130 try {
131 // Use with(scope) { return (body) } to allow body to reference names
132 return Function('scope', 'with(scope){ return (' + def.body + ') }')(local);
133 } catch (e) {
134 // propagate error
140 // Now evaluate expression in the scope
141 try {
142 return Function('scope', 'with(scope){ return (' + expr + ') }')(scope);
143 } catch (e) {
144 throw e;
148 /************************************************************************
149 * Parse the document top-down:
150 * - function defs f(a,b)=...
151 * - variable defs name = rhs (rhs may be quoted string OR an expression)
152 *
153 * We evaluate variables in document order so earlier defs are available to later ones.
154 ************************************************************************/
155 function parseDocument(doc) {
156 rawVars.clear();
157 functions.clear();
158 computedVars.clear();
159
163 if (!line) continue;
164
165 // function: name(arg1, arg2) = body
166 const fm = line.match(/^([A-Za-z_][\\w]*)\\s*\\(([^)]*)\\)\\s*=\\s*(.+)$/);
167 if (fm) {
169 const params = fm[2].split(',').map(s=>s.trim()).filter(Boolean);
170 const body = fm[3].trim();
171 functions.set(name, { params, body });
172 continue;
173 }
180 rawVars.set(name, rhs);
181
182 // attempt to evaluate using current environment (earlier vars + functions)
183 try {
184 let value;
275 }, { decorations: v => v.decorations });
276
277 function stringifyValue(v) {
278 if (v === null || v === undefined) return String(v);
279 if (typeof v === 'number') {

location-feed-generatorcheckins.ts10 matches

@tijsโ€ขUpdated 56 mins ago
19 * Convert API PlaceInput to proper Place object
20 */
21function _sanitizePlaceInput(input: PlaceInput): Place {
22 const latitude = typeof input.latitude === "string"
23 ? parseFloat(input.latitude)
52}
53
54async function _getEnhancedAddressRecord(
55 place: Place,
56): Promise<CommunityAddressRecord> {
139}
140
141// Helper function to authenticate user with Iron Session (both web and mobile)
142async function authenticateUser(
143 c: Context,
144): Promise<{ did: string; oauthSession: any } | null> {
207
208// Create a checkin with address using StrongRef architecture
209export async function createCheckin(c: Context): Promise<Response> {
210 try {
211 // Authenticate user with Iron Session
289}
290
291// Helper function to extract rkey from AT Protocol URI
292function extractRkey(uri: string): string {
293 const parts = uri.split("/");
294 return parts[parts.length - 1];
296
297// Create address and checkin records via AT Protocol using clean OAuth API
298async function createAddressAndCheckin(
299 sessions: OAuthSessionsInterface,
300 did: string,
466}
467
468// Simple function to get a checkin by ID for frontend routes
469export async function getCheckinById(checkinId: string) {
470 try {
471 const results = await db.select().from(checkinsTable)

zoomtestmain.js7 matches

@yawnxyzโ€ขUpdated 58 mins ago
279 let timerInterval;
280
281 function startTimer() {
282 startTime = Date.now();
283 timerInterval = setInterval(updateTimer, 10);
284 }
285
286 function stopTimer() {
287 clearInterval(timerInterval);
288 const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(2);
291 }
292
293 function updateTimer() {
294 const elapsedTime = ((Date.now() - startTime) / 1000).toFixed(2);
295 timerDisplay.textContent = elapsedTime + 's';
296 }
297
298 function updateStats(text) {
299 const encoder = new TextEncoder();
300 const utf8 = new Uint8Array(text.length * 3);
339 }
340
341 function adjustInputTextareaHeight() {
342 inputText.style.height = 'auto';
343 inputText.style.height = inputText.scrollHeight + 10 + 'px';
350
351
352 async function updateHistoryList() {
353 const history = await db.history.reverse().limit(50).toArray();
354 historyList.innerHTML = history.map(item =>
386 });
387
388 // Accordion functionality
389 document.querySelectorAll('[id^="accordion-"]').forEach(button => {
390 button.addEventListener('click', () => {

zoomtest.cursorrules12 matches

@yawnxyzโ€ขUpdated 1 hour ago
4
5- 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
20
21## Types of triggers
28
29```ts
30export default async function (req: Request) {
31 return new Response("Hello World");
32}
42
43```ts
44export default async function () {
45 // Scheduled task code
46}
56
57```ts
58export default async function (email: Email) {
59 // Process email
60}
66## Val Town Standard Libraries
67
68Val Town provides several hosted services and utility functions.
69
70### Blob Storage
120```
121
122## Val Town Utility Functions
123
124Val Town provides several utility functions to help with common project tasks.
125
126### 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```
223
226- 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
230 import { 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
263
264## Common Gotchas and Solutions

flowxo-http-bot-samplebot.ts1 match

@flowxoโ€ขUpdated 1 hour ago
51});
52
53function sendToWorkvivo(message: any, channel: string) {
54 const payload = {
55 bot_userid: BOT_USER_ID,

chatterchatStream.js3 matches

@yawnxyzโ€ขUpdated 1 hour ago
5import { serverApiKey } from "../config.js";
6
7function collectToolTextFromArray(toolArray) {
8 if (!Array.isArray(toolArray)) return '';
9 const parts = [];
10 for (const t of toolArray) {
11 try {
12 const name = t?.name || t?.tool || t?.function?.name || t?.id || '';
13 const args = t?.arguments || t?.input || t?.params || null;
14 const output = t?.output || t?.result || t?.content || null;
23}
24
25export function registerChatStreamRoute(app) {
26 app.post('/api/chatStream', async (c) => {
27 try {

chatterjobs.js13 matches

@yawnxyzโ€ขUpdated 1 hour ago
25let jobCounter = 0;
26
27function now() { return Date.now(); }
28
29function newJobId() {
30 jobCounter += 1;
31 return String(now()) + "-" + String(jobCounter);
32}
33
34function createJob(type, input) {
35 const id = newJobId();
36 const job = {
52}
53
54function getJob(id) { return jobs.get(String(id)); }
55
56function publish(job, eventName, payload) {
57 const encoder = new TextEncoder();
58 const data = (payload === undefined) ? "" : JSON.stringify(payload);
63}
64
65function completeJob(job, result) {
66 job.status = "completed";
67 job.updatedAt = now();
73}
74
75function failJob(job, message) {
76 job.status = "error";
77 job.updatedAt = now();
82}
83
84function cancelJob(job) {
85 try { job.abortController && job.abortController.abort(); } catch (_) { /* ignore */ }
86 job.status = "cancelled";
91}
92
93async function runChatJob(job) {
94 const input = job.input || {};
95 const {
282}
283
284function tryParseJson(s) {
285 try { return JSON.parse(s); } catch (_) { return { raw: s }; }
286}
287
288function collectToolTextFromArray(toolArray) {
289 if (!Array.isArray(toolArray)) return '';
290 const parts = [];
291 for (const t of toolArray) {
292 try {
293 const name = t?.name || t?.tool || t?.function?.name || t?.id || '';
294 const args = t?.arguments || t?.input || t?.params || null;
295 const output = t?.output || t?.result || t?.content || null;
304}
305
306export function registerJobsRoutes(app) {
307 // Create job
308 app.post('/api/jobs', async (c) => {

chatterchatCompletion.js6 matches

@yawnxyzโ€ขUpdated 1 hour ago
1// Minimal Groq Chat Completions client using fetch
2import { extractOrRepairJsonResults, extractStructuredSummary, renderStructuredSummaryToHtml } from "./jsonUtils.js";
3export async function groqChatCompletion(apiKey, payload) {
4 console.log('>>> [groqChatCompletion] Payload:', payload);
5 const response = await fetch('https://api.groq.com/openai/v1/chat/completions', {
22// extractOrRepairJsonResults moved to ./jsonUtils.js
23
24export function buildSearchPrompt(query, source, dateRange, language, offset) {
25 // Always search in English; present in the selected language
26 const presentationLanguage = (typeof language === 'string' && language.trim()) ? language : 'english';
50
51// Lightweight router: decide between 'links' (JSON list) and 'text' (short answer)
52export async function routeQueryMode(apiKey, query) {
53 // Routing disabled: force plain chat mode
54 return 'text';
77}
78
79export async function performSearch({ apiKey, query, dateRange, source, language, offset = 0, model, stream, reasoningEffort, forceLinksRoute = false }) {
80 // const prompt = buildSearchPrompt(query, source, dateRange, language, offset);
81 // const start = Date.now();
128import { marked } from "npm:marked";
129
130function buildSummaryPrompt(url, title, language) {
131 const languageInstruction = language && language !== 'english'
132 ? `Please provide the summary in ${language}. `
167}
168
169export async function summarizeUrl({ apiKey, url, title, language, model, stream, reasoningEffort }) {
170 const summaryPrompt = buildSummaryPrompt(url, title, language);
171 const start = Date.now();

chatterchatStreamSSE.js3 matches

@yawnxyzโ€ขUpdated 1 hour ago
4import { serverApiKey } from "../config.js";
5
6function collectToolTextFromArray(toolArray) {
7 if (!Array.isArray(toolArray)) return '';
8 const parts = [];
9 for (const t of toolArray) {
10 try {
11 const name = t?.name || t?.tool || t?.function?.name || t?.id || '';
12 const args = t?.arguments || t?.input || t?.params || null;
13 const output = t?.output || t?.result || t?.content || null;
22}
23
24export function registerChatStreamSSERoute(app) {
25 app.post('/api/chatStreamSSE', async (c) => {
26 try {

ratelimit4 file matches

@unkeyโ€ขUpdated 1 month ago
Rate limit your serverless functions

discordWebhook2 file matches

@stevekrouseโ€ขUpdated 2 months ago
Helper function to send Discord messages
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.