twitterCardsmain.tsx2 matches
1import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON?v=45";
23interface TwitterPost {
18const url =
19"https://publish.twitter.com/oembed?url=https%3A%2F%2Ftwitter.com%2FInterior%2Fstatus%2F507185938620219395";
20const res = (await fetchJSON(url)) as TwitterPost;
2122return new Response(res.html, { headers: { "content-type": "text/html" } });
utilitiesemptyValUtils.ts3 matches
1import { fetchPaginatedData } from "https://esm.town/v/nbbaier/fetchPaginatedData";
2import { deleteVal } from "https://esm.town/v/neverstew/deleteVal";
34export async function listEmptyVals(id: string) {
5const token = Deno.env.get("valtown");
6const res = await fetchPaginatedData(`https://api.val.town/v1/users/${id}/vals`, {
7headers: { Authorization: `Bearer ${token}` },
8});
12export async function deleteEmptyVals(id: string) {
13const token = Deno.env.get("valtown");
14const res = await fetchPaginatedData(`https://api.val.town/v1/users/${id}/vals`, {
15headers: { Authorization: `Bearer ${token}` },
16});
dbToAPI_backupexample.tsx1 match
4const app = await createServer(db);
56export default app.fetch;
FarcasterMiniAppStoreHome.tsx4 matches
67import { Button, Input, Section, ShareButton } from "../components/ui.tsx";
8import { fetchNeynarGet, fetchNeynarGetPages, fetchUsersById } from "../util/neynar.ts";
9import { useQuery } from "../util/useQuery.ts";
1038function MiniApps() {
39const { data: miniapps } = useQuery(["miniapps"], async () => {
40// return await fetch(`/api/miniapps`).then(r => r.json()).then(r => r);
41// return await fetchNeynarGet(`frame/catalog?limit=100`).then(r => r.frames);
42return await fetchNeynarGetPages(`frame/catalog?limit=100`, 4, "frames").then(r => r.frames);
43});
44
perplexityAPImain.tsx2 matches
1import { PplxRequest, PplxResponse } from "https://esm.town/v/nbbaier/perplexityAPI/pplxTypes.ts";
2import { fetchJSON } from "https://esm.town/v/stevekrouse/fetchJSON";
34export const pplx = async (options: PplxRequest & { apiKey?: string }): Promise<PplxResponse> => {
5const token = options.apiKey ? options.apiKey : Deno.env.get("PERPLEXITY_API_KEY");
6return await fetchJSON("https://api.perplexity.ai/chat/completions", {
7method: "POST",
8headers: {
projectTreemain.tsx1 match
26});
2728export default app.fetch;
7import { Hono } from "npm:hono";
8import { html } from "npm:hono/html";
9import { fetch } from "npm:node-fetch";
10import { z } from "npm:zod";
11// --- Constants ---
7071/**
72* Gets data from cache or fetches it if expired/missing.
73* @param cacheKey - Unique key for the cached data.
74* @param fetchFn - Async function to fetch data if cache is invalid.
75* @param apiKey - API key, used to determine if live fetch is possible.
76* @param steps - Log array.
77* @returns The fetched or cached data.
78*/
79async function getCachedData<T>(
80cacheKey: string,
81fetchFn: () => Promise<T>,
82apiKey: string | undefined | null,
83steps: string[],
113114if (!apiKey) {
115steps.push(`API key missing for ${cacheKey}, cannot fetch fresh data.`);
116if (cachedData) {
117steps.push(`Returning expired cached data for ${cacheKey} as fallback.`);
123124steps.push(`Workspaceing fresh data for ${cacheKey}`);
125// TODO: error handling: Handle potential errors during the actual fetchFn execution
126try {
127const freshData = await fetchFn();
128const newTimestamp = Date.now();
129// TODO: error handling: Handle potential SQLite errors during INSERT/REPLACE
133args: [cacheKey, JSON.stringify(freshData), newTimestamp],
134});
135steps.push(`Successfully fetched and cached data for ${cacheKey}`);
136} catch (e: any) {
137steps.push(`Error writing to cache for ${cacheKey}: ${e.message}`);
139}
140return freshData;
141} catch (fetchError: any) {
142steps.push(`Error fetching fresh data for ${cacheKey}: ${fetchError.message}`);
143if (cachedData) {
144steps.push(`Returning expired cached data for ${cacheKey} due to fetch error.`);
145return cachedData; // Return stale data if fetch fails
146}
147throw new Error(`Failed to fetch data for ${cacheKey} and no cache available: ${fetchError.message}`);
148}
149}
150151/**
152* Fetches historical stock data from Alpha Vantage.
153* @param ticker - Stock ticker symbol.
154* @param apiKey - Alpha Vantage API key.
156* @returns Parsed Alpha Vantage time series data or null.
157*/
158async function fetchAlphaVantageData(
159ticker: string,
160apiKey: string | undefined | null,
162): Promise<AlphaVantageTimeSeriesData | null> {
163const cacheKey = `alphavantage_${ticker}`;
164const fetchFn = async () => {
165steps.push(`Workspaceing Alpha Vantage data for ${ticker}`);
166// TODO: error handling: Handle potential fetch errors (network, non-200 status)
167const url =
168`https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=${ticker}&outputsize=full&apikey=${apiKey}`;
169const response = await fetch(url);
170if (!response.ok) {
171throw new Error(`Alpha Vantage API error: ${response.statusText} (Status: ${response.status})`);
185};
186187return getCachedData(cacheKey, fetchFn, apiKey, steps);
188}
189190/**
191* Fetches previous day's close price from Polygon.io.
192* @param ticker - Stock ticker symbol.
193* @param apiKey - Polygon.io API key.
195* @returns Parsed Polygon previous close data or null.
196*/
197async function fetchPolygonData(
198ticker: string,
199apiKey: string | undefined | null,
201): Promise<PolygonPreviousCloseData | null> {
202const cacheKey = `polygon_${ticker}`;
203const fetchFn = async () => {
204steps.push(`Workspaceing Polygon.io data for ${ticker}`);
205// TODO: error handling: Handle potential fetch errors (network, non-200 status)
206const url = `https://api.polygon.io/v2/aggs/ticker/${ticker}/prev?adjusted=true&apiKey=${apiKey}`;
207const response = await fetch(url);
208if (!response.ok) {
209let errorBody = await response.text();
225};
226227return getCachedData(cacheKey, fetchFn, apiKey, steps);
228}
229390const { ticker, alphaVantageKey, polygonKey } = validatedInput;
391392// 2. Fetch Data
393steps.push("Fetching data");
394// TODO: error handling: These fetches might return null or throw errors
395let alphaVantageData: AlphaVantageTimeSeriesData | null = null;
396let polygonData: PolygonPreviousCloseData | null = null;
397let fetchError: Error | null = null;
398399try {
400[alphaVantageData, polygonData] = await Promise.all([
401fetchAlphaVantageData(ticker, alphaVantageKey || null, steps),
402fetchPolygonData(ticker, polygonKey || null, steps),
403]);
404} catch (error: any) {
405steps.push(`Error during data fetching: ${error.message}`);
406fetchError = error;
407// Attempt to continue if some data was fetched (e.g., from cache fallback)
408if (!alphaVantageData)
409alphaVantageData = await fetchAlphaVantageData(ticker, alphaVantageKey || null, steps).catch(() => null); // Try again individually, catch error
410if (!polygonData) polygonData = await fetchPolygonData(ticker, polygonKey || null, steps).catch(() => null); // Try again individually, catch error
411}
412413if (!alphaVantageData && !polygonData && fetchError) {
414// If both fetches failed critically and no cache fallback was possible, rethrow
415throw fetchError;
416}
417500const data = Object.fromEntries(formData.entries());
501502// Use the current URL for the fetch endpoint
503const url = new URL(window.location.href);
504url.pathname += '/analyze'; // Append /analyze to the current path
505506try {
507const response = await fetch(url.toString(), {
508method: 'POST',
509headers: {
559};
560561// Mock fetch to avoid actual API calls and simulate responses
562const originalFetch = global.fetch;
563global.fetch = (url: string, options?: any): Promise<any> => {
564console.log(`Mock fetch called for: ${url}`);
565let responseData: any = {};
566let status = 200;
603statusText: status === 200 ? "OK" : "Error",
604json: () => Promise.resolve(responseData),
605text: () => Promise.resolve(JSON.stringify(responseData)), // For error handling in polygon fetch
606});
607};
629console.error("Self-test FAILED with error:", error);
630} finally {
631// Restore original fetch
632global.fetch = originalFetch;
633console.log("Self-test finished.");
634}
84tickerDataMap: Map<string, TickerData>;
85newsSentiment?: Record<string, "Positive" | "Neutral" | "Negative" | "Error">;
86fetchErrors?: Record<string, string>;
87}
88interface TaskInput<T> {
306try {
307var apiUrl = window.location.pathname + '?action=analyze_goals&format=json';
308var res = await fetch(apiUrl, {
309method: 'POST',
310headers: { 'Content-Type': 'application/json', },
427}
428429async function fetchTickerDataFromYahoo(
430ticker: string,
431range = "1y",
433): Promise<TickerData> {
434const interval = "1d";
435const logPfx = `YahooFetch [${ticker}, ${range}]`;
436internalLog(`${logPfx}: Init fetch...`);
437try {
438if (!/^[A-Z0-9.-]+$/.test(ticker)) {
451url.searchParams.set("includeTimestamps", "true");
452url.searchParams.set("events", "div,splits");
453internalLog(`${logPfx}: [INFO] Fetching: ${url}`);
454const opts = {
455method: "GET",
463},
464};
465const res = await fetch(url.toString(), opts);
466const resText = await res.text();
467let jsonData;
480const errDet = res.ok ? "Missing chart.result" : `HTTP ${res.status}`;
481internalLog(`${logPfx}: [ERROR] No valid data. Detail: ${errDet}. Resp: ${resText.substring(0, 100)}...`);
482return { ticker, error: `Failed fetch: ${errDet}`, dates: [], open: [], high: [], low: [], close: [], volume: [] };
483}
484const result = jsonData.chart.result[0];
513volume: combined.map(d => d.volume),
514};
515internalLog(`${logPfx}: [SUCCESS] Fetched ${data.dates.length} valid data points.`);
516return data;
517} catch (err: any) {
518internalLog(`${logPfx}: [CRITICAL ERROR] Unexpected fetch failure: ${err.message}`);
519console.error(`${logPfx} Error:`, err);
520return { ticker, error: `Unexpected fetch error: ${err.message}`, dates: [], open: [], high: [], low: [], close: [], volume: [] };
521}
522}
704}
705706async function runContextDataFetchingAgent(
707task: TaskInput<{ tickers: string[]; data_needed: string[] }>,
708log: LogFunction,
709): Promise<TaskOutput<ContextData>> {
710const agentName = "ContextDataFetchingAgent";
711const taskId = task.taskId;
712const { tickers: reqTickers, data_needed } = task.payload;
715"INFO",
716agentName,
717`Task ${taskId}. Fetching ${data_needed.join(", ")} for ${tickers.length} tickers: ${tickers.join(", ")}`,
718);
719const intLog = (msg: string) => log("DEBUG", agentName, `[${taskId}] ${msg}`);
720const tickerDataMap = new Map<string, TickerData>();
721const fetchErrs: Record<string, string> = {};
722let newsSent: Record<string, "Positive" | "Neutral" | "Negative" | "Error"> | undefined;
723let sysErr: string | undefined;
724if (data_needed.includes("yahoo_1y")) {
725const promises = tickers.map(t => fetchTickerDataFromYahoo(t, "1y", intLog));
726try {
727const results = await Promise.all(promises);
728results.forEach(d => {
729tickerDataMap.set(d.ticker, d);
730if (d.error) { fetchErrs[d.ticker] = `Yahoo Error: ${d.error}`; }
731});
732const successCount = tickers.length - Object.keys(fetchErrs).length;
733log(
734"INFO",
735agentName,
736`Yahoo fetch completed for ${taskId}. ${successCount} successful, ${Object.keys(fetchErrs).length} errors.`,
737);
738if (successCount === 0 && tickers.length > 0) {
739log("ERROR", agentName, `Yahoo fetch FAILED for ALL tickers in task ${taskId}.`);
740}
741} catch (e: any) {
742log("ERROR", agentName, `Critical error during parallel Yahoo fetch for task ${taskId}`, e);
743sysErr = `Parallel fetch execution failed: ${e.message}`;
744fetchErrs["SYSTEM"] = sysErr;
745}
746} else { log("WARN", agentName, `Task ${taskId} skipped 'yahoo_1y' data fetch.`); }
747if (data_needed.includes("market_news_sentiment") && !sysErr) {
748log("INFO", agentName, `Simulating news sentiment fetch for task ${taskId}...`);
749newsSent = {};
750await new Promise(r => setTimeout(r, 50 + Math.random() * 50));
751for (const t of tickers) {
752const r = Math.random();
753if (fetchErrs[t]) {
754newsSent[t] = "Error";
755if (!fetchErrs[t]?.includes("News")) fetchErrs[t] += "; News Error: Skipped due to prior error";
756} else if (r < 0.05) {
757newsSent[t] = "Error";
758fetchErrs[t] = (fetchErrs[t] ? `${fetchErrs[t]}; ` : "") + "News Error: Simulated fetch failure";
759} else if (r < 0.35) { newsSent[t] = "Negative"; }
760else if (r < 0.75) { newsSent[t] = "Neutral"; }
764} else if (data_needed.includes("market_news_sentiment") && sysErr) {
765log("WARN", agentName, `Skipping news sentiment simulation for task ${taskId} due to prior system error.`);
766} else { log("WARN", agentName, `Task ${taskId} skipped 'market_news_sentiment' data fetch.`); }
767return {
768mandateId: task.mandateId,
769correlationId: taskId,
770senderRole: "Responsible",
771payload: { tickerDataMap, newsSentiment: newsSent, fetchErrors: fetchErrs },
772error: sysErr,
773};
1245}
1246await this.internalLog("SUCCESS", `Received suggested tickers: ${intRes.suggestedTickers.join(", ")}`);
1247const fetchDataTask: TaskInput<{ tickers: string[]; data_needed: string[] }> = {
1248mandateId: this.mandateId, taskId: `TSK-Fetch-${Date.now()}`, senderRole: "Orchestrator", recipientRole: "Responsible",
1249payload: { tickers: intRes.suggestedTickers, data_needed: ["yahoo_1y", "market_news_sentiment"] },
1250};
1251await this.internalLog("STEP", `Requesting context data (Yahoo, News Sim). Task ID: ${fetchDataTask.taskId}`);
1252const fetchDataOut = await runContextDataFetchingAgent(fetchDataTask, this.log);
1253await this.auditAgentTaskResult("ContextDataFetchingAgent", fetchDataOut);
1254if (fetchDataOut.error) { throw new Error(`Context Data Fetching Failed (System): ${fetchDataOut.error}`); }
1255intRes.contextData = fetchDataOut.payload;
1256const tickersWithData = intRes.suggestedTickers.filter(t =>
1257!intRes.contextData?.fetchErrors?.[t] &&
1258intRes.contextData?.tickerDataMap.has(t) &&
1259(intRes.contextData?.tickerDataMap.get(t)?.close?.length ?? 0) > 0
1260);
1261if (tickersWithData.length === 0) {
1262throw new Error(`Context Data Fetching Failed: No valid data retrieved for any suggested ticker. Errors: ${JSON.stringify(intRes.contextData?.fetchErrors)}`);
1263}
1264await this.internalLog("INFO", `Context data retrieved for ${tickersWithData.length} tickers. Failed/Skipped: ${intRes.suggestedTickers.length - tickersWithData.length}`);
1322const predResult = allPreds.find(p => p.ticker === ticker);
1323if (!quantResult || quantResult.error) {
1324const errorMsg = `Skipped due to ${quantResult ? 'Quant failure: ' + quantResult.error : 'Data fetch failure: ' + (intRes.contextData?.fetchErrors?.[ticker] || 'Unknown reason')}`;
1325if (!interpResult) {
1326allInterps.push({ ticker, error: `Interpretation ${errorMsg}`, summary: "", indicatorInterpretation: "", volatilityAssessment: "", alignmentWithGoals: "", confidence: "Low", newsContextSentiment: "N/A" });
the-juicestill-olive-barnacle4 matches
2223useEffect(() => {
24fetchWorld();
25}, []);
2627const fetchWorld = async () => {
28const response = await fetch('/generate');
29const data = await response.json();
30setWorld(data.world);
41</div>
42))}
43<button onClick={fetchWorld}>Generate New World</button>
44<p><a href={import.meta.url.replace("esm.town", "val.town")}>View Source</a></p>
45</div>
stevensDemosendDailyBrief.ts1 match
135const lastSunday = today.startOf("week").minus({ days: 1 });
136137// Fetch relevant memories using the utility function
138const memories = await getRelevantMemories();
139