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=542&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 20202 results for "function"(3702ms)

smsberthandleSmsMessage.ts5 matches

@vincenzo•Updated 4 weeks ago
30 * Store a chat message in the database
31 */
32export async function storeChatMessage(
33 chatId,
34 senderId,
63 * Retrieve chat history for a specific chat
64 */
65export async function getChatHistory(chatId, limit = 50) {
66 try {
67 const { sqlite } = await import("https://esm.town/v/stevekrouse/sqlite");
88 * Format chat history for Anthropic API
89 */
90function formatChatHistoryForAI(history) {
91 const messages = [];
92
112 * Analyze a Telegram message and extract memories from it
113 */
114async function analyzeMessageContent(
115 anthropic,
116 username,
498
499// Handle webhook requests
500export default async function(req: Request): Promise<Response> {
501 // Set webhook if it is not set yet
502 if (req.method === "POST") {

Thinkingmain.tsx10 matches

@Get•Updated 4 weeks ago
67Synthesize these inputs into a clear summary. Briefly recap the key points from each hat used. Conclude with a statement about the overall thinking process or potential next steps based on the analysis. Start directly with the synthesis. Avoid using backticks (\`).`;
68
69// --- HTML Generation Function (Adapted for ThinkingFlow) ---
70function generateHtmlShell(initialQuery, initialSequence, sourceUrl) {
71 const escapedQuery = initialQuery.replace(/"/g, "&quot;");
72 const escapedSequence = initialSequence.replace(/"/g, "&quot;");
178 const submitButtonText = submitButton.querySelector('span');
179
180 // Function to safely escape HTML
181 function escapeHTML(str) {
182 const p = document.createElement('p');
183 p.textContent = str;
186
187 // Render conversation log
188 function renderConversation(log) {
189 if (!log || log.length === 0) {
190 conversationDiv.innerHTML = '<p style="text-align:center; color: #546e7a;">No thinking process data received.</p>';
236
237 // Show client errors
238 function showClientError(message) {
239 errorContainer.innerHTML = ''; // Clear previous errors
240 const errorDiv = document.createElement('div');
333
334// --- Main Request Handler (Server Code for ThinkingFlow MVP) ---
335export default async function(req: Request) {
336 // Dynamic Import of OpenAI Library
337 const { OpenAI } = await import("https://esm.town/v/std/openai");
338
339 // --- OpenAI API Call Helper (Reused) ---
340 async function callOpenAI(
341 systemPrompt: string,
342 userMessage: string, // Can be query or intermediate context
377
378 // --- Helper: Map Hat Code to Prompt and Name ---
379 function getHatDetails(hatCode: string): { name: string; prompt: string } {
380 switch (hatCode.toUpperCase()) {
381 case "W":
397
398 // --- Helper: Run the ThinkingFlow Workflow ---
399 async function runThinkingFlow(
400 userQuery: string,
401 sequenceString: string,

belle-energie-checkercheckNewTarif.cron.ts1 match

@pom421•Updated 4 weeks ago
22
23// deno-lint-ignore no-unused-vars
24export default async function (interval: Interval) {
25 try {
26 const getEtagResponse = await getEtag();

Lifesyncmain.tsx11 matches

@Get•Updated 4 weeks ago
102Combine the key points from the agent responses into a unified message. Start with a brief acknowledgement of the user's query. Then, integrate the advice logically. Ensure the final output flows well and directly addresses the user's core need. Avoid repetition. If any agent failed or provided an error, briefly mention that that aspect couldn't be addressed fully. End with an encouraging closing statement. Keep the overall tone holistic and supportive. Avoid using backticks (\`) in your response.`;
103
104// --- HTML Generation Function (Generates the initial page structure and client-side JS) ---
105// Includes updates for LifeSync agents and styling
106function generateHtmlShell(initialQuery, sourceUrl) {
107 const escapedQuery = initialQuery.replace(/"/g, "&quot;");
108 const currentDate = new Date().toLocaleDateString(); // Get current date
201 const submitButtonText = submitButton.querySelector('span');
202
203 function renderConversation(log) {
204 if (!log || log.length === 0) {
205 conversationDiv.innerHTML = '<p style="text-align:center; color: #6c757d;">No conversation data received.</p>';
246 }
247
248 function showClientError(message) {
249 errorContainer.innerHTML = ''; // Clear previous errors
250 const errorDiv = document.createElement('div');
321// --- Main Request Handler (Server Code) ---
322// Includes LifeSync agent flow
323export default async function(req: Request) {
324 const { OpenAI } = await import("https://esm.town/v/std/openai");
325
326 // --- Helper Function: Call OpenAI API ---
327 // (Mostly unchanged, but updated the JSON mode check)
328 async function callOpenAI(
329 systemPrompt: string,
330 userMessage: string,
390 }
391
392 // --- Helper Function: Map Domain to Agent Details ---
393 function getAgentDetails(domain: string): { name: string; prompt: string; icon: string } {
394 switch (domain.toUpperCase()) {
395 case "VISIONARY":
416 }
417
418 // --- Helper Function: Run the LifeSync Multi-Agent Workflow ---
419 async function runAgentFlow(userQuery: string): Promise<Array<{ agent: string; message: string }>> {
420 const conversationLog: Array<{ agent: string; message: string }> = [];
421

stevensDemotestDailyBrief.ts1 match

@jed•Updated 4 weeks 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

@jed•Updated 4 weeks 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

@jed•Updated 4 weeks 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

@jed•Updated 4 weeks 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

@jed•Updated 4 weeks 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.

stevensDemoqueries.ts4 matches

@jed•Updated 4 weeks ago
6const tableName = "memories_demo";
7
8export async function getAllMemories(): Promise<Memory[]> {
9 const result = await sqlite.execute(
10 `SELECT id, date, text, createdBy, createdDate, tags FROM ${tableName}
23}
24
25export async function createMemory(
26 memory: Omit<Memory, "id">
27): Promise<Memory> {
51}
52
53export async function updateMemory(
54 id: string,
55 memory: Partial<Omit<Memory, "id">>
70}
71
72export async function deleteMemory(id: string): Promise<void> {
73 await sqlite.execute(`DELETE FROM ${tableName} WHERE id = ?`, [id]);
74}

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.