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/$%7BsvgDataUrl%7D?q=function&page=79&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 31571 results for "function"(4245ms)

Louai_performance_orchestrator.ts5 matches

@jeffvincentUpdated 5 days ago
50
51// ============================================================================
52// MAIN REVIEW FUNCTION
53// ============================================================================
54
55/**
56 * Main function for AI team performance review
57 */
58export async function reviewTeamPerformance(
59 userId: string,
60 leagueId: string,
194
195/**
196 * Quick analysis function for testing
197 */
198export async function quickTeamAnalysis(
199 userId: string,
200 leagueId: string,

Louai_performance_api.ts8 matches

@jeffvincentUpdated 5 days ago
25 * GET /scheduler/status - Get scheduler status
26 */
27export default async function handler(request: Request): Promise<Response> {
28 const url = new URL(request.url);
29 const method = request.method;
115 * Query params: userId, leagueId, teamKey, options (optional JSON)
116 */
117async function handleAnalyzeRequest(request: Request, corsHeaders: Record<string, string>): Promise<Response> {
118 try {
119 const url = new URL(request.url);
216 * GET /analysis/{userId}
217 */
218async function handleGetAnalysis(userId: string, corsHeaders: Record<string, string>): Promise<Response> {
219 try {
220 console.log(`📊 API: Retrieving latest analysis for user ${userId}`);
265 * GET /health
266 */
267async function handleHealthCheck(corsHeaders: Record<string, string>): Promise<Response> {
268 try {
269 const schedulerSummary = await getSchedulerSummary();
304 * Body: SchedulerConfig
305 */
306async function handleAddSchedule(request: Request, corsHeaders: Record<string, string>): Promise<Response> {
307 try {
308 const config = await request.json();
363 * Body: { userId, leagueId }
364 */
365async function handleRemoveSchedule(request: Request, corsHeaders: Record<string, string>): Promise<Response> {
366 try {
367 const { userId, leagueId } = await request.json();
408 * GET /scheduler/status
409 */
410async function handleSchedulerStatus(corsHeaders: Record<string, string>): Promise<Response> {
411 try {
412 const summary = await getSchedulerSummary();
438 * GET /
439 */
440async function handleApiDocumentation(corsHeaders: Record<string, string>): Promise<Response> {
441 const docs = {
442 title: "AI Fantasy Baseball Performance Analysis API",

Louai_performance_scheduler.ts11 matches

@jeffvincentUpdated 5 days ago
37
38/**
39 * Main cron scheduler function for AI performance analysis
40 * Configure this as a cron job in Val.town
41 */
42export async function aiPerformanceAnalysisCron(): Promise<void> {
43 console.log("🤖 Starting scheduled AI performance analysis...");
44 const startTime = Date.now();
110 * Process a single scheduled analysis configuration
111 */
112async function processScheduledAnalysis(config: SchedulerConfig): Promise<any> {
113 console.log(`🔍 Processing analysis for user ${config.userId}, league ${config.leagueId}`);
114
191 * Get scheduler configurations from storage
192 */
193async function getSchedulerConfigs(): Promise<SchedulerConfig[]> {
194 try {
195 const configs = await blob.getJSON("ai_performance_scheduler_configs");
204 * Store analysis result for later retrieval
205 */
206async function storeAnalysisResult(result: StoredAnalysisResult): Promise<void> {
207 try {
208 const key = `ai_analysis_result_${result.userId}_${result.timestamp.replace(/[:.]/g, '_')}`;
221 * Store execution summary for monitoring
222 */
223async function storeExecutionSummary(summary: any): Promise<void> {
224 try {
225 const key = `ai_scheduler_summary_${summary.timestamp.replace(/[:.]/g, '_')}`;
237 * Send email notification with analysis results
238 */
239async function sendEmailNotification(config: SchedulerConfig, analysisResult: any): Promise<void> {
240 try {
241 const hasRecommendations = analysisResult.recommendations && analysisResult.recommendations.length > 0;
311 * Add or update a scheduler configuration
312 */
313export async function addSchedulerConfig(config: SchedulerConfig): Promise<void> {
314 try {
315 const configs = await getSchedulerConfigs();
335 * Remove a scheduler configuration
336 */
337export async function removeSchedulerConfig(userId: string, leagueId: string): Promise<void> {
338 try {
339 const configs = await getSchedulerConfigs();
354 * Get latest analysis result for a user
355 */
356export async function getLatestAnalysis(userId: string): Promise<StoredAnalysisResult | null> {
357 try {
358 const key = `ai_analysis_latest_${userId}`;
368 * Get scheduler execution summary
369 */
370export async function getSchedulerSummary(): Promise<any> {
371 try {
372 const summary = await blob.getJSON("ai_scheduler_latest_summary");

Louai_performance_prompts.ts28 matches

@jeffvincentUpdated 5 days ago
212 * Generate system context information for analysis
213 */
214function generateSystemContext(leagueContext?: PerformancePromptContext['leagueContext'], timeContext?: PerformancePromptContext['timeContext']): string {
215 if (!leagueContext && !timeContext) return '';
216
240 * Generate comprehensive team overview section
241 */
242function generateTeamOverview(teamStats: TeamPerformanceStats, leagueContext?: PerformancePromptContext['leagueContext']): string {
243 return `
244TEAM PERFORMANCE OVERVIEW:
254 * Generate roster composition analysis
255 */
256function generateRosterAnalysis(teamStats: TeamPerformanceStats, playerStats: PlayerPerformanceStats[]): string {
257 const batters = playerStats.filter(p => p.position_type === 'B').length;
258 const pitchers = playerStats.filter(p => p.position_type === 'P').length;
271 * Generate recent performance trends
272 */
273function generateRecentPerformanceData(teamStats: TeamPerformanceStats): string {
274 if (!teamStats.recent_performance?.last_5_weeks) return '';
275
290 * Generate detailed player performance data
291 */
292function generatePlayerPerformanceDetails(playerStats: PlayerPerformanceStats[], verbosity: PromptConfig['verbosityLevel']): string {
293 const sortedStats = [...playerStats].sort((a, b) =>
294 (b.performance_metrics?.avg_fantasy_points || 0) - (a.performance_metrics?.avg_fantasy_points || 0)
313 * Generate waiver analysis context
314 */
315function generateWaiverAnalysisContext(
316 teamStats: TeamPerformanceStats,
317 competitiveContext?: PickupPromptContext['competitiveContext'],
344 * Generate roster needs analysis
345 */
346function generateRosterNeedsAnalysis(rosterNeeds: PickupPromptContext['rosterNeeds'], underperformers: PlayerPerformanceStats[]): string {
347 return `
348ROSTER NEEDS ASSESSMENT:
356 * Generate waiver candidates data section
357 */
358function generateWaiverCandidatesData(candidates: WaiverWirePlayer[]): string {
359 const sortedCandidates = [...candidates]
360 .sort((a, b) => (b.fantasy_relevance_score || 0) - (a.fantasy_relevance_score || 0))
376 * Generate underperformers analysis
377 */
378function generateUnderperformersAnalysis(underperformers: PlayerPerformanceStats[]): string {
379 if (underperformers.length === 0) return '\nDROP CANDIDATES: No clear underperformers identified.';
380
397 * Generate analysis instructions based on configuration
398 */
399function generateAnalysisInstructions(config: PromptConfig): string {
400 const instructions = `
401ANALYSIS REQUIREMENTS:
419 * Generate pickup analysis instructions
420 */
421function generatePickupAnalysisInstructions(config: PromptConfig): string {
422 return `
423PICKUP ANALYSIS METHODOLOGY:
443 * Generate the expected JSON output schema for performance analysis
444 */
445function generateOutputSchema(): string {
446 return `
447REQUIRED JSON OUTPUT STRUCTURE:
521 * Generate the expected JSON output schema for pickup recommendations
522 */
523function generatePickupOutputSchema(): string {
524 return `
525REQUIRED JSON OUTPUT STRUCTURE:
603 * Generate example performance analysis for reference
604 */
605function generatePerformanceAnalysisExamples(): string {
606 return `
607EXAMPLE ANALYSIS OUTPUT:
620 * Generate example pickup recommendations for reference
621 */
622function generatePickupRecommendationExamples(): string {
623 return `
624EXAMPLE PICKUP RECOMMENDATION:
652
653// ============================================================================
654// HELPER FUNCTIONS
655// ============================================================================
656
658 * Get default prompt configuration
659 */
660function getDefaultConfig(): PromptConfig {
661 return {
662 model: 'gpt-4-turbo-preview',
672 * Get player form description based on recent performance
673 */
674function getPlayerFormDescription(player: PlayerPerformanceStats): string {
675 const consistency = player.performance_metrics?.consistency_score || 50;
676 if (consistency >= 80) return 'Excellent';
683 * Get player trend description for waiver candidates
684 */
685function getPlayerTrendDescription(player: WaiverWirePlayer): string {
686 if (player.fantasy_relevance_score && player.fantasy_relevance_score > 75) return 'Hot';
687 if (player.fantasy_relevance_score && player.fantasy_relevance_score < 25) return 'Cold';
692 * Get player issues description for underperformers
693 */
694function getPlayerIssuesDescription(player: PlayerPerformanceStats): string {
695 const issues = [];
696
711
712// ============================================================================
713// VALIDATION FUNCTIONS
714// ============================================================================
715
717 * Validate performance prompt inputs
718 */
719function validatePerformancePromptInputs(context: PerformancePromptContext): PromptValidationResult {
720 const errors: string[] = [];
721 const warnings: string[] = [];
774 * Validate pickup prompt inputs
775 */
776function validatePickupPromptInputs(context: PickupPromptContext): PromptValidationResult {
777 const errors: string[] = [];
778 const warnings: string[] = [];
831
832// ============================================================================
833// UTILITY FUNCTIONS
834// ============================================================================
835
840 * @returns Model-optimized prompt
841 */
842export function optimizePromptForModel(prompt: string, model: PromptConfig['model']): string {
843 switch (model) {
844 case 'gpt-4o':
862 * @returns Estimated token count
863 */
864export function estimateTokenCount(prompt: string): number {
865 // Rough estimate: ~4 characters per token for English text
866 return Math.ceil(prompt.length / 4);
873 * @returns Truncated prompt if necessary
874 */
875export function truncatePromptForTokenLimit(prompt: string, maxTokens: number): string {
876 const estimatedTokens = estimateTokenCount(prompt);
877
901 * Create a prompt configuration for different use cases
902 */
903export function createPromptConfig(useCase: 'performance' | 'pickups' | 'quick'): PromptConfig {
904 const baseConfig = getDefaultConfig();
905

Loudaily_lineup_scheduler.tsx3 matches

@jeffvincentUpdated 5 days ago
1// Lou Fantasy Baseball Daily Lineup Scheduler
2// Val.town Cron Function for Daily Pitcher Optimization
3
4import { LouTokenStorage, StoredTokens } from "./oauth/token_storage.tsx";
1544}
1545
1546// Val.town Cron Handler - This function will be called by Val.town's cron scheduler
1547export default async function(): Promise<Response> {
1548 console.log('🕒 Daily lineup scheduler cron job triggered');
1549
879
880// ============================================================================
881// CONVENIENCE FACTORY FUNCTION
882// ============================================================================
883
887 * @returns Configured OpenAI client
888 */
889export function createOpenAIClient(config?: Partial<OpenAIConfig>): LouOpenAIClient {
890 return new LouOpenAIClient(config);
891}
900 * @returns Validation result
901 */
902export function validatePerformanceData(data: {
903 teamStats: TeamPerformanceStats;
904 playerStats: PlayerPerformanceStats[];
931 * @returns Validation result
932 */
933export function validateWaiverData(
934 lowPerformers: PlayerPerformanceStats[],
935 candidates: WaiverWirePlayer[]

Loumain.tsx1 match

@jeffvincentUpdated 5 days ago
2// Main entry point for Val.town deployment
3
4export default function App() {
5 return (
6 <div>

Louoauth_callback.ts2 matches

@jeffvincentUpdated 5 days ago
3import { LouTokenStorage } from "./token_storage.tsx";
4
5export default async function(req: Request): Promise<Response> {
6 console.log("OAuth callback endpoint called");
7
185}
186
187function createErrorResponse(title: string, message: string, suggestion: string): Response {
188 return new Response(
189 `

Louoauth_auth.ts1 match

@jeffvincentUpdated 5 days ago
2import { LouOAuthHandler } from "./oauth_handler.ts";
3
4export default async function(req: Request): Promise<Response> {
5 console.log("OAuth auth endpoint called");
6

ChatmcpTesting.ts4 matches

@c15rUpdated 5 days ago
18 * @returns Promise<MCPTestResult>
19 */
20export async function testMCPServer(server: MCPServerConfig, clientPool: MCPClientPool): Promise<MCPTestResult> {
21 if (!server.url) {
22 return {
50 * @returns Promise<Record<string, MCPTestResult>>
51 */
52export async function testMCPServers(servers: MCPServerConfig[], clientPool: MCPClientPool): Promise<Record<string, MCPTestResult>> {
53 const enabledServers = servers.filter(server => server.enabled && server.url);
54
75
76/**
77 * Legacy function for backward compatibility - creates direct fetch test
78 * @deprecated Use testMCPServer with clientPool instead
79 */
80export async function testMCPServerDirect(server: MCPServerConfig): Promise<MCPTestResult> {
81 if (!server.url) {
82 return {
tuna

tuna9 file matches

@jxnblkUpdated 2 weeks ago
Simple functional CSS library for Val Town

getFileEmail4 file matches

@shouserUpdated 2 months ago
A helper function to build a file's email
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.