39);
4041// token middleware for API requests
42app.all("/api/*", async (c, next) => {
43const sessionCookie = getCookie(c, "_session");
44if (!sessionCookie) {
50});
5152app.route("/api", backend);
5354app.get("/frontend/*", c => {
1import { basicAuthMiddleware } from "./auth.ts";
2import { handleApiRequest } from "./api/index.ts";
3import { getRequests } from "./api/requests.ts";
4import { getUserSummary } from "./api/user-summary.ts";
5import { getInferenceCalls } from "./api/inference-calls.ts";
6import { renderDashboard } from "./views/dashboard.ts";
7import { renderRequests } from "./views/requests.ts";
22const path = url.pathname;
2324// Handle API requests
25if (path.startsWith("/api/")) {
26return handleApiRequest(req);
27}
28
45/**
6* Handle API requests
7*/
8export async function handleApiRequest(req: Request): Promise<Response> {
9const url = new URL(req.url);
10const path = url.pathname.replace("/api/", "");
11
12try {
13// Route to the appropriate API handler
14if (path === "requests") {
15const usageId = url.searchParams.get("usage_id");
59}
60} catch (error) {
61console.error("API error:", error);
62return new Response(JSON.stringify({ error: error.message }), {
63status: 500,
42</h2>
43<ol>
44<li>Login with your Val Town API token (with projects:read, projects:write, user:read permissions)</li>
45<li>Select a project to work on</li>
46<li>Chat with Claude about your code</li>
79</div>
80<h3>Cost Tracking</h3>
81<p>See estimated API usage costs for each interaction</p>
82</div>
83</section>
92<ul>
93<li>React frontend with TypeScript</li>
94<li>Hono API server backend</li>
95<li>Web Audio API for sound notifications</li>
96<li>AI SDK for Claude integration</li>
97</ul>
98<p>
99The application proxies requests to the Anthropic API and Val Town API, allowing Claude to view and edit your
100project files directly.
101</p>
social_data_api_projectproxy-api.ts23 matches
1/**
2* SocialData API Proxy for Cloudflare Workers
3* Acts as a backend for the X Search UI, handling API key management,
4* and request forwarding to SocialData API.
5*
6* This proxy runs on Cloudflare Workers and connects to:
7* - Supabase for authentication and user management
8* - Cloudflare D1 for tweet storage
9* - SocialData API for Twitter/X data
10*/
1141try {
42// Supabaseの公開鍵を使ってJWTを検証するのが理想ですが、
43// 簡易的な実装としてSupabase APIを利用して検証します
44const supabaseUrl = env.SUPABASE_URL;
45const supabaseKey = env.SUPABASE_SERVICE_KEY;
50}
5152// Supabase Auth APIを利用してユーザー情報を取得
53const response = await fetch(`${supabaseUrl}/auth/v1/user`, {
54headers: {
55"Authorization": `Bearer ${token}`,
56"apikey": supabaseKey,
57},
58});
69headers: {
70"Authorization": `Bearer ${supabaseKey}`,
71"apikey": supabaseKey,
72},
73});
104105/**
106* Forward request to SocialData API
107* @param {string} query - Search query
108* @param {string} type - Search type (Latest or Top)
113async function forwardToSocialData(query, type, cursor, env) {
114try {
115const apiKey = env.SOCIAL_DATA_API_KEY;
116if (!apiKey) {
117throw new Error("SOCIAL_DATA_API_KEY environment variable not set");
118}
119120const apiUrl = new URL("https://api.socialdata.tools/twitter/search");
121apiUrl.searchParams.set("query", query);
122apiUrl.searchParams.set("type", type || "Latest");
123if (cursor) {
124apiUrl.searchParams.set("cursor", cursor);
125}
126127const response = await fetch(apiUrl.toString(), {
128headers: {
129"Authorization": `Bearer ${apiKey}`,
130"Accept": "application/json",
131},
136try {
137const errorData = await response.json();
138errorText = errorData.message || `API Error: ${response.statusText}`;
139} catch {
140errorText = `API Error: ${response.statusText}`;
141}
142throw new Error(errorText);
167"Content-Type": "application/json",
168"Authorization": `Bearer ${supabaseKey}`,
169"apikey": supabaseKey,
170"Prefer": "return=minimal",
171},
344ctx.waitUntil(incrementSearchCount(authResult.userId, env));
345346// Forward request to SocialData API
347const data = await forwardToSocialData(query, type, cursor, env);
348450JSON.stringify({
451status: "ok",
452message: "SocialData API Proxy is running",
453environment: "Cloudflare Workers",
454}),
562}
563564const apiRequestBody: any = { model, messages: messagesPayload };
565if (typeof params.temperature === "number") apiRequestBody.temperature = params.temperature;
566if (typeof params.max_tokens === "number" && params.max_tokens > 0)
567apiRequestBody.max_tokens = Math.floor(params.max_tokens);
568569log("INFO", "OpenAiCallTool", "Making OpenAI chat completion call.", {
576577try {
578const completion = await openaiClient.chat.completions.create(apiRequestBody);
579if (!completion?.choices?.length) {
580log("WARN", "OpenAiCallTool", "OpenAI response empty/unexpected.", { response: completion });
583return { mandateId, correlationId: taskId, payload: { result: completion } };
584} catch (e: any) {
585log("ERROR", "OpenAiCallTool", "OpenAI API call failed.", e);
586const errMsg = e.response?.data?.error?.message || e.error?.message || e.message || "Unknown OpenAI API error";
587return { mandateId, correlationId: taskId, payload: { result: null }, error: errMsg };
588}
701const { mandateId, taskId, payload } = input;
702const { log } = context;
703log("INFO", "ScrapeEmails", `Scraping emails for ${payload.businesses?.length ?? 0} sites.`);
704705if (!payload?.businesses || !Array.isArray(payload.businesses)) {
753await delay(WEBSITE_VISIT_DELAY_MS);
754}
755log("SUCCESS", "ScrapeEmails", `Scraping done. Found emails for ${foundLeads.length} leads.`);
756return { mandateId, correlationId: taskId, payload: { leads: foundLeads } };
757}
810} catch (error: any) {
811log("ERROR", "DraftEmails", `Failed for ${lead.name}: ${error.message}`, error);
812finalLeads.push({ ...lead, draftedEmail: "[OpenAI API call failed]" });
813}
814await delay(300); // Small delay between OpenAI calls
1117<body><h1>Superpowered Agent Platform - Lead Gen Demo</h1>
1118<p>Runs <code>leadGenWorkflowV1</code>. See <a href="/">Original V3 Demo</a>.</p>
1119<p><strong>Note:</strong> Google Search is simulated. Scraping is basic.</p>
1120<form id="leadGenForm">
1121<label for="searchQuery">Search Query (Required):</label><input type="text" id="searchQuery" name="searchQuery" required value="dentists in Los Angeles">
ipv4-counterindex.ts2 matches
15await initDatabase();
1617// API endpoint to get visit data
18app.get("/api/visits", async (c) => {
19const visits = await getAllVisits();
20const totalVisits = await getTotalVisits();
226227// Add engagement filters
228// Always use min_ (greater than or equal to) for API filters
229if (likesCount) {
230finalQuery += ` min_faves:${likesCount}`;
236237// Note: Replies count, bookmark count, and views count might not be directly filterable
238// in the Twitter/X API. These may need to be filtered client-side after fetching.
239240return finalQuery.trim();
272maxTweets: parseInt(maxTweets),
273filters: {
274// These filters will be applied client-side if the API doesn't support them directly
275// Always use "greater than or equal to" filtering
276repliesCount: repliesCount
380// Helper to check if a tweet meets the client-side filter criteria
381const meetsCriteria = (tweet) => {
382// Apply any client-side filters here that the API doesn't support
383// Only perform "greater than or equal to" checks
384401}
402403// Apply like count filter if not handled by API
404if (likesCount && tweet.favorite_count !== undefined) {
405if (tweet.favorite_count < parseInt(likesCount)) return false;
406}
407408// Apply retweet count filter if not handled by API
409if (retweetsCount && tweet.retweet_count !== undefined) {
410if (tweet.retweet_count < parseInt(retweetsCount)) return false;
StarterPackFeedsimage.tsx3 matches
8485const loadEmoji = (code) => {
86// const api = `https://cdnjs.cloudflare.com/ajax/libs/twemoji/14.0.2/svg/${code.toLowerCase()}.svg`
87const api = `https://cdn.jsdelivr.net/gh/shuding/fluentui-emoji-unicode/assets/${code.toLowerCase()}_color.svg`;
88return fetch(api).then((r) => r.text());
89};
90
ipv4-counterindex.html1 match
125document.getElementById('refresh-btn').addEventListener('click', async () => {
126try {
127const response = await fetch('/api/visits');
128const data = await response.json();
129updateUI(data);