122return generatedData;
123} catch (error) {
124console.error("Error fetching or processing data from OpenAI:", error);
125console.warn("Using fallback race data due to the error.");
126// Ensure fallback data also has the hint, slice correctly
592errorInvalidFile: "Invalid file type. Please upload a PDF.",
593errorFileSize: "File is too large (Max {maxSize}).",
594errorFetchFailed: "Failed to perform analysis: {errorMessage}",
595// Contact Placeholders
596contactNamePlaceholder: "Your Name",
651errorInvalidFile: "Tipo de archivo inválido. Por favor, suba un PDF.",
652errorFileSize: "El archivo es demasiado grande (Máx {maxSize}).",
653errorFetchFailed: "Falló la realización del análisis: {errorMessage}",
654// Contact Placeholders
655contactNamePlaceholder: "Tu Nombre",
851852try {
853const response = await fetch(window.location.pathname + '?format=json', { method: 'POST', headers: { 'Accept': 'application/json'}, body: formData });
854updateLoadingProgress(25, 'loadingStatusAnalysis'); // Adjusted percentage
855const data = await response.json();
884} catch (error) {
885console.error('Analysis Request Error:', error);
886displayError('errorFetchFailed', { errorMessage: error.message });
887resultsContent.style.display = 'none'; // Ensure results area hidden on error
888noResultsMessage.style.display = 'block';
918const { OpenAI } = await import("https://esm.town/v/std/openai");
919const { z } = await import("npm:zod");
920const { fetch } = await import("https://esm.town/v/std/fetch");
921const { PDFExtract, PDFExtractOptions } = await import("npm:pdf.js-extract");
9221001try {
1002log.push({ agent, type: "step", message: `Workspaceing: ${url}` });
1003const res = await fetch(url, {
1004headers: { "User-Agent": "ValTownPolicyAnalysisBot/1.0" },
1005redirect: "follow",
1074try {
1075if (!input.documentUrl.match(/^https?:\/\//i)) throw new Error("Invalid URL scheme.");
1076const res = await fetch(input.documentUrl, {
1077headers: { "Accept": "text/plain, text/html, application/pdf", "User-Agent": "ValTownPolicyAnalysisBot/1.0" },
1078redirect: "follow",
1091} else if (ct.includes("text/") || ct === "") {
1092const text = await res.text();
1093if (!text?.trim()) throw new Error("Fetched empty text.");
1094log.push({ agent: ingestAgent, type: "result", message: `Workspaceed ~${text.length} chars.` });
1095docText = text;
1096} else { throw new Error(`Unsupported content type: ${ct}`); }
1097} catch (e) {
1098log.push({ agent: ingestAgent, type: "error", message: `URL fetch/process failed: ${e.message}` });
1099docText = null;
1100}
whatDoYouThinkOfItSoFarmain.tsx2 matches
1import { email } from "https://esm.town/v/std/email";
2import { fetchText } from "https://esm.town/v/stevekrouse/fetchText?v=6";
3import { type Document, DOMParser, type Node } from "jsr:@b-fuze/deno-dom";
44243export default (interval: Interval) => {
44fetchText(
45Deno.env.get("rubbish_url")
46).then(html => {
84interface TraversedCitation extends Citation {
85traversalStatus: "success" | "not_attempted" | "failed" | "url_missing";
86fetchedContentSummary?: string;
87error?: string;
88}
291292try {
293const response = await fetch(window.location.pathname + '?format=json', {
294method: 'POST',
295headers: { 'Accept': 'application/json' },
341const { OpenAI } = await import("https://esm.town/v/std/openai");
342const { z } = await import("npm:zod");
343const { fetch } = await import("https://esm.town/v/std/fetch");
344// Import the PDF extraction library
345const { PDFExtract, PDFExtractOptions } = await import("npm:pdf.js-extract");
441for (const citation of citations) {
442// Basic URL validation and prepending https:// if missing protocol
443let urlToFetch = citation.potentialUrl;
444if (urlToFetch) {
445try {
446// Attempt to construct a URL to validate/normalize it
447const parsedUrl = new URL(urlToFetch.startsWith("http") ? urlToFetch : `https://${urlToFetch}`);
448urlToFetch = parsedUrl.href; // Use the normalized URL
449} catch (_) {
450log.push({ agent, type: "error", message: `Invalid potential URL format: ${citation.potentialUrl}` });
457let errorMsg: string | undefined = undefined;
458try {
459log.push({ agent, type: "step", message: `Workspaceing reference: ${urlToFetch}` });
460const response = await fetch(urlToFetch, {
461headers: { "User-Agent": "ValTownPolicyAnalysisBot/1.0" },
462redirect: "follow",
465if (!response.ok) throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`);
466status = "success";
467log.push({ agent, type: "result", message: `Successfully accessed: ${urlToFetch}` });
468} catch (error) {
469errorMsg = `Failed to fetch reference ${urlToFetch}: ${error.message}`;
470log.push({ agent, type: "error", message: errorMsg });
471status = "failed";
472}
473results.push({ ...citation, potentialUrl: urlToFetch, traversalStatus: status, error: errorMsg }); // Store normalized URL
474} else { results.push({ ...citation, traversalStatus: "url_missing" }); }
475}
524log.push({ agent: ingestionAgent, type: "step", message: `Workspaceing from URL: ${input.documentUrl}` });
525try {
526const response = await fetch(input.documentUrl, { headers: { "Accept": "text/plain, text/html" } });
527if (!response.ok) throw new Error(`HTTP error! status: ${response.status} ${response.statusText}`);
528const text = await response.text();
529if (!text || text.trim().length === 0) throw new Error("Fetched content is empty or not text.");
530log.push({
531agent: ingestionAgent,
535documentText = text;
536} catch (error) {
537const errorMessage = `Failed to fetch or process URL ${input.documentUrl}: ${error.message}`;
538log.push({ agent: ingestionAgent, type: "error", message: errorMessage });
539documentText = null;
67import { OpenAI } from "https://esm.town/v/std/openai";
8// import { Request, Response } from "https://esm.town/v/std/fetch"; // Usually global
910// --- Define Expected Data Structures ---
50// --- ***** THIS FUNCTION WAS MISSING ***** ---
51// --- OpenAI Generation Function ---
52// Asynchronously fetches race data from OpenAI's Chat Completion API.
53async function generateRaceDataWithOpenAI(): Promise<RaceInfo[]> {
54let openai;
136}));
137} catch (error) {
138console.error("Error fetching or processing data from OpenAI:", error);
139if (error.constructor.name === "AuthenticationError") {
140console.error("OpenAI Authentication Error: Check 'openai' secret.");
152console.log("Server function started."); // Log start
153154// 1. Fetch Race Data - Ensure this line is calling the function defined above
155console.log("Attempting to fetch race data...");
156const activeRaceData = await generateRaceDataWithOpenAI();
157console.log(`Workspaceed ${activeRaceData.length} races. First race: ${activeRaceData[0]?.name || "N/A"}`);
1// Service for fetching data from Manifold API
2interface Answer {
3id: string;
265266/**
267* Fetches comments for a specific market from Manifold API
268*/
269async function fetchMarketComments(marketId: string): Promise<Comment[]> {
270try {
271console.log(`Fetching comments for market ${marketId}`);
272const url = `https://api.manifold.markets/v0/comments?contractId=${marketId}&limit=1000`;
273console.log(`Fetching from URL: ${url}`);
274
275const response = await fetch(url);
276
277if (!response.ok) {
305return [];
306} catch (error) {
307console.error("Error fetching comments:", error);
308return [];
309}
311312/**
313* Fetches player data from Manifold API and categorizes them
314*/
315export async function fetchPlayerData(): Promise<PlayerData | null> {
316try {
317// Fetch market data from Manifold API
318const marketResponse = await fetch(`https://api.manifold.markets/v0/market/${MARKET_ID}`);
319
320if (!marketResponse.ok) {
328}
329
330// Separately fetch comments
331const comments = await fetchMarketComments(MARKET_ID);
332console.log(`Fetched ${comments.length} comments`);
333
334// Extract player positions from comments if available
426};
427} catch (error) {
428console.error("Error fetching player data:", error);
429return null;
430}
parkingSpotsmain.tsx2 matches
1import { fetch } from "https://esm.town/v/std/fetch";
23export function parkingSpots(lat, lng, radius = 5) {
4return fetch(
5`https://park4night.com/api/places/around?lat=${lat}&lng=${lng}&radius=${radius}&filter=%7B%7D&lang=en`,
6).then((res) => res.json());
MiniAppStarterneynar.ts14 matches
1const baseUrl = "https://api.neynar.com/v2/farcaster/";
23export async function fetchNeynarGet(path: string) {
4const res = await fetch(baseUrl + path, {
5method: "GET",
6headers: {
14}
1516export function fetchUser(username: string) {
17return fetchNeynarGet(`user/by_username?username=${username}`).then(r => r.user);
18}
19export function fetchUsersById(fids: string) {
20return fetchNeynarGet(`user/bulk?fids=${fids}`).then(r => r.users);
21}
2223export function fetchUserFeed(fid: number) {
24return fetchNeynarGet(
25`feed?feed_type=filter&filter_type=fids&fids=${fid}&with_recasts=false&with_replies=false&limit=100&cursor=`,
26).then(r => r.casts);
27}
2829export function fetchChannel(channelId: string) {
30return fetchNeynarGet(`channel?id=${channelId}`).then(r => r.channel);
31}
3233export function fetchChannelFeed(channelId: string) {
34return fetchNeynarGet(
35`feed/channels?channel_ids=${channelId}&with_recasts=false&limit=100`,
36).then(r => r.casts);
37}
3839export function fetchChannelsFeed(channelIds: array) {
40return fetchNeynarGet(
41`feed/channels?channel_ids=${channelIds.join(",")}&with_recasts=false&limit=100`,
42).then(r => r.casts);
MiniAppStarterindex.tsx2 matches
63});
6465// HTTP vals expect an exported "fetch handler"
66// This is how you "run the server" in Val Town with Hono
67export default app.fetch;