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/$%7Bart_info.art.src%7D?q=fetch&page=79&format=json

For typeahead suggestions, use the /typeahead endpoint:

https://codesearch.val.run/typeahead?q=fetch

Returns an array of strings in format "username" or "username/projectName"

Found 8567 results for "fetch"(1308ms)

Projectmain.tsx22 matches

@Get•Updated 1 week ago
85interface TraversedCitation extends Citation {
86 traversalStatus: "success" | "not_attempted" | "failed" | "url_missing";
87 fetchedContentSummary?: string; // Note: Original code didn't fetch summary, only status
88 error?: string;
89}
479 errorInvalidFile: "Invalid file type. Please upload a PDF.",
480 errorFileSize: "File is too large (Max {maxSize}).", // Updated to use replacement
481 errorFetchFailed: "Failed to perform analysis: {errorMessage}", // Placeholder for dynamic message
482 analysisTitle: "Analysis Results", // Keep if needed elsewhere, dashboard cards have own titles now
483 loadingAnalysis: "Analyzing Document...",
515 errorInvalidFile: "Tipo de archivo inválido. Por favor, suba un PDF.",
516 errorFileSize: "El archivo es demasiado grande (Máx {maxSize}).", // Updated
517 errorFetchFailed: "Falló la realización del análisis: {errorMessage}",
518 analysisTitle: "Resultados del Análisis",
519 loadingAnalysis: "Analizando Documento...",
819
820 try {
821 // Fetch from the current location, expecting the Val to handle POST
822 const response = await fetch(window.location.pathname + '?format=json', { // Ensure format=json is requested
823 method: 'POST',
824 headers: { 'Accept': 'application/json'}, // Crucial: Tell server we want JSON back
909 console.error('Analysis Request Error:', error);
910 // Use the specific error message from the caught error
911 displayError('errorFetchFailed', { errorMessage: error.message });
912 resultsArea.style.display = 'none';
913 } finally {
952 const { OpenAI } = await import("https://esm.town/v/std/openai");
953 const { z } = await import("npm:zod");
954 const { fetch } = await import("https://esm.town/v/std/fetch");
955 // Import the PDF extraction library
956 const { PDFExtract, PDFExtractOptions } = await import("npm:pdf.js-extract");
1040 const traversalPromises = citations.map(async (citation): Promise<TraversedCitation> => {
1041 if (citation.potentialUrl) {
1042 traversedCount++; // Increment here is slightly inaccurate if fetch fails early, but simpler
1043 let status: TraversedCitation["traversalStatus"] = "failed";
1044 let errorMsg: string | undefined = undefined;
1045 let urlToFetch = citation.potentialUrl;
1046 // Basic URL validation/fixing
1047 if (!urlToFetch.startsWith('http://') && !urlToFetch.startsWith('https://')) {
1048 urlToFetch = 'http://' + urlToFetch; // Default to http if protocol missing
1049 }
1050
1051 try {
1052 // Log the attempt for this specific URL
1053 log.push({ agent, type: "step", message: `Attempting to fetch: ${urlToFetch}` });
1054 const response = await fetch(urlToFetch, {
1055 headers: { "User-Agent": "ValTownPolicyAnalysisBot/1.0 (+http://val.town)" }, // Be a good bot citizen
1056 redirect: "follow", // Follow redirects
1065 status = "success";
1066 // Log success for this URL
1067 log.push({ agent, type: "result", message: `Successfully accessed: ${urlToFetch}` });
1068 return { ...citation, potentialUrl: urlToFetch, traversalStatus: status, error: undefined };
1069 } catch (error) {
1070 errorMsg = `Workspace failed for ${urlToFetch}: ${error.message.substring(0, 100)}`; // Keep error msg concise
1071 // Log failure for this URL
1072 log.push({ agent, type: "error", message: errorMsg });
1073 status = "failed";
1074 return { ...citation, potentialUrl: urlToFetch, traversalStatus: status, error: errorMsg };
1075 }
1076 } else {
1149 log.push({ agent: ingestionAgent, type: "step", message: \`Workspaceing from URL: \${input.documentUrl}\` });
1150 try {
1151 // Basic check for common non-HTTP URL schemes that fetch will reject
1152 if (!input.documentUrl.match(/^https?:\/\//i)) {
1153 throw new Error("Invalid URL scheme. Only http and https are supported.");
1154 }
1155 const response = await fetch(input.documentUrl, {
1156 headers: { "Accept": "text/plain, text/html, application/pdf", "User-Agent": "ValTownPolicyAnalysisBot/1.0" },
1157 redirect: "follow",
1158 timeout: 10000 // 10 second timeout for fetching
1159 });
1160 if (!response.ok) throw new Error(\`HTTP error! Status: \${response.status} \${response.statusText}\`);
1171 } else if (contentType.includes("text/html") || contentType.includes("text/plain") || contentType === "") { // Allow empty content type
1172 const text = await response.text();
1173 if (!text || text.trim().length === 0) throw new Error("Fetched content is empty or not text.");
1174 log.push({
1175 agent: ingestionAgent,
1185
1186 } catch (error) {
1187 const errorMessage = \`Failed to fetch or process URL \${input.documentUrl}: \${error.message}\`;
1188 log.push({ agent: ingestionAgent, type: "error", message: errorMessage });
1189 documentText = null;
vtProjectSearch

vtProjectSearchimport.ts3 matches

@dcm31•Updated 1 week ago
27 if (userId && !processedUsers.has(userId)) {
28 try {
29 // Fetch user data
30 const user = await vt.users.retrieve(userId);
31
43 processedUsers.add(userId);
44 } catch (error) {
45 console.error(`Error fetching user ${userId}:`, error);
46 // Continue with val processing even if user fetch fails
47 }
48 }

myanythingmain.tsx1 match

@yassinreg•Updated 1 week ago
25
26 try {
27 const response = await fetch(window.location.href, {
28 method: 'POST',
29 body: formData

myeverythingmain.tsx1 match

@yassinreg•Updated 1 week ago
25
26 try {
27 const response = await fetch(window.location.href, {
28 method: "POST",
29 body: formData,

feedbackmain.tsx1 match

@yassinreg•Updated 1 week ago
25
26 try {
27 const response = await fetch(window.location.href, {
28 method: "POST",
29 body: formData,

FixItWandindex.http.ts1 match

@wolf•Updated 1 week ago
18 });
19
20export default app.fetch;

daily-advice-appmain.tsx4 matches

@dcm31•Updated 1 week ago
7 const [loading, setLoading] = useState(false);
8
9 async function fetchAdvice() {
10 setLoading(true);
11 try {
12 const res = await fetch("https://api.adviceslip.com/advice");
13 const data = await res.json();
14 setAdvice(data.slip.advice);
21
22 useEffect(() => {
23 fetchAdvice();
24 }, []);
25
32 </p>
33 <button
34 onClick={fetchAdvice}
35 className="mt-6 bg-blue-500 hover:bg-blue-600 text-white font-semibold py-2 px-4 rounded w-full"
36 disabled={loading}

mini-remixrender.tsx1 match

@probablycorey•Updated 1 week ago
56 e.preventDefault()
57 const form = e.currentTarget as HTMLFormElement
58 const res = await fetch(form.action || window.location.href, {
59 method: form.method || "POST",
60 body: new FormData(form),

moiPosterImprovedMoiEditor.tsx7 matches

@dcm31•Updated 1 week ago
8 disabled?: boolean;
9 username?: string; // Username prop to set default author
10 valId?: string; // Val ID for fetching endpoints
11 apiToken?: string; // Token for API requests
12}
62 const initializedRef = useRef(false);
63
64 // Fetch HTTP endpoints if available
65 useEffect(() => {
66 if (!valId || !apiToken) return;
67
68 const fetchEndpoints = async () => {
69 setLoadingEndpoints(true);
70 setEndpointsError(null);
71
72 try {
73 const response = await fetch(`/api/vals/${valId}/endpoints`, {
74 headers: { 'Authorization': `Bearer ${apiToken}` }
75 });
76
77 if (!response.ok) {
78 throw new Error(`Failed to fetch endpoints: ${response.statusText}`);
79 }
80
82 setEndpoints(data.endpoints || []);
83 } catch (error) {
84 console.error('Error fetching endpoints:', error);
85 setEndpointsError(error instanceof Error ? error.message : 'Unknown error');
86 } finally {
89 };
90
91 fetchEndpoints();
92 }, [valId, apiToken]);
93

moiPosterImprovedApp.tsx29 matches

@dcm31•Updated 1 week ago
34 const [tokenError, setTokenError] = useState<string | null>(null);
35 const [username, setUsername] = useState<string>("");
36 // Flag to track if we've already tried to fetch data
37 const [initialFetchDone, setInitialFetchDone] = useState(false);
38 // Editor key for forcing re-render
39 const [editorKey, setEditorKey] = useState<string>("editor-0");
57 }, [apiToken]);
58
59 // Fetch user information to get username
60 const fetchUserInfo = useCallback(async () => {
61 if (!apiToken) return;
62
63 try {
64 const response = await fetch(`/api/user`, {
65 headers: { "Authorization": `Bearer ${apiToken}` },
66 });
74 }
75 } catch (error) {
76 console.warn("Could not fetch user info:", error);
77 // Non-critical error, don't show to user
78 }
79 }, [apiToken]);
80
81 const fetchVals = useCallback(async () => {
82 if (!apiToken) {
83 setError("Val Town API Key is required to list your vals.");
84 setLoading(false);
85 setVals([]);
86 setInitialFetchDone(true);
87 return;
88 }
97 try {
98 const queryParams = filterPrivacy !== "all" ? `?privacy=${filterPrivacy}` : "";
99 const response = await fetch(`/api/vals${queryParams}`, {
100 headers: { "Authorization": `Bearer ${apiToken}` },
101 });
108 setVals([]);
109 } else {
110 setError(`Failed to fetch vals: ${errorData.error || response.statusText}`);
111 }
112 throw new Error(`Failed to fetch vals (Status: ${response.status})`);
113 }
114 const data = await response.json();
121 }
122 } catch (err) {
123 console.error(`Error fetching vals:`, err);
124 if (!error && !tokenError) {
125 setError(`Failed to load vals. Please try again later.`);
127 } finally {
128 setLoading(false);
129 setInitialFetchDone(true);
130 }
131 }, [apiToken, filterPrivacy, initialFetchDone, error, tokenError]);
132
133 // Run initial fetch only once when API token is available
134 useEffect(() => {
135 if (apiToken && !initialFetchDone && !loading) {
136 fetchUserInfo();
137 fetchVals();
138 }
139 }, [apiToken, initialFetchDone, loading, fetchUserInfo, fetchVals]);
140
141 const handleValSelect = async (val: Val) => {
165 try {
166 const valId = val.id;
167 const response = await fetch(`/api/vals/${valId}/moi`);
168 if (!response.ok) {
169 const errorData = await response.json().catch(() => ({ error: `HTTP error ${response.status}` }));
170 throw new Error(errorData.error || "Failed to fetch moi.md");
171 }
172 const data: MoiFile = await response.json();
179 pendingSaveContentRef.current = initialContent;
180 } catch (err) {
181 console.error("Error fetching moi.md:", err);
182 setItemError(`Failed to fetch moi.md content: ${err instanceof Error ? err.message : String(err)}`);
183 if (selectedVal) {
184 const defaultContent = generateDefaultMoiContent(selectedVal);
274 console.log("Updating existing moi.md file");
275 // Update existing moi.md file using the current API endpoint
276 const response = await fetch(`/api/vals/${valId}/moi`, {
277 method: "POST",
278 headers: { "Content-Type": "application/json", "Authorization": `Bearer ${apiToken}` },
296 console.log("Creating new moi.md file");
297 // Create new moi.md file for vals that don't have one yet
298 const response = await fetch(`/api/vals/${valId}/file`, {
299 method: "POST",
300 headers: { "Content-Type": "application/json", "Authorization": `Bearer ${apiToken}` },
327
328 // Refresh the vals list to show updated status
329 fetchVals();
330
331 setTimeout(() => setSaveSuccess(false), 3000);
351 setApiToken(newToken);
352
353 // Reset the initialFetchDone flag if the token changes
354 if (newToken !== apiToken) {
355 setInitialFetchDone(false);
356 }
357 };
443 {/* Refresh Button: Aqua background, Black text */}
444 <button
445 onClick={fetchVals}
446 disabled={loading || !apiToken}
447 className={`px-3 py-1.5 rounded-md text-sm transition-colors text-[#000000] ${

fetchPaginatedData2 file matches

@nbbaier•Updated 2 weeks ago

FetchBasic1 file match

@fredmoon•Updated 2 weeks ago