Towniequeries.tsx5 matches
24user_id = ?
25AND timestamp > ?
26AND our_api_token = 1
27`,
28[userId, new Date().getTime() - 24 * 60 * 60 * 1000],
113branch_id,
114model,
115our_api_token,
116num_images,
117}: {
120branch_id: string;
121model: string;
122our_api_token: boolean;
123num_images: number;
124}) {
132branch_id,
133model,
134our_api_token,
135num_images
136) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
143branch_id,
144model,
145our_api_token ? 1 : 0,
146num_images,
147],
41);
4243// token middleware for API requests
44app.all("/api/*", async (c, next) => {
45const sessionCookie = getCookie(c, "_session");
46if (!sessionCookie) {
52});
5354app.route("/api", backend);
5556app.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,
32<ol>
33<li>
34Login with your Val Town API token (with projects:read, projects:write, user:read permissions)
35</li>
36<li>Select a project to work on</li>
70</div>
71<h3>Cost Tracking</h3>
72<p>See estimated API usage costs for each interaction</p>
73</div>
74</section>
79<ul>
80<li>React frontend with TypeScript</li>
81<li>Hono API server backend</li>
82<li>Web Audio API for sound notifications</li>
83<li>AI SDK for Claude integration</li>
84</ul>
85<p>
86The application proxies requests to the Anthropic API and Val Town API, allowing Claude to view and edit your
87project files directly.
88</p>
Townie.cursorrules10 matches
13- Generate code in TypeScript or TSX
14- Add appropriate TypeScript types and interfaces for all data structures
15- Prefer official SDKs or libraries than writing API calls directly
16- Ask the user to supply API or library documentation if you are at all unsure about it
17- **Never bake in secrets into the code** - always use environment variables
18- Include comments explaining complex logic (avoid commenting obvious operations)
23### 1. HTTP Trigger
2425- Create web APIs and endpoints
26- Handle HTTP requests and responses
27- Example structure:
173However, it's *extremely importing* to note that `parseProject` and other Standard Library utilities ONLY RUN ON THE SERVER.
174If you need access to this data on the client, run it in the server and pass it to the client by splicing it into the HTML page
175or by making an API request for it.
176177## Val Town Platform Specifics
181- **AI Image:** To inline generate an AI image use: `<img src="https://maxm-imggenurl.web.val.run/the-description-of-your-image" />`
182- **Storage:** DO NOT use the Deno KV module for storage
183- **Browser APIs:** DO NOT use the `alert()`, `prompt()`, or `confirm()` methods
184- **Weather Data:** Use open-meteo for weather data (doesn't require API keys) unless otherwise specified
185- **View Source:** Add a view source link by importing & using `import.meta.url.replace("ems.sh", "val.town)"` (or passing this data to the client) and include `target="_top"` attribute
186- **Error Debugging:** Add `<script src="https://esm.town/v/std/catch"></script>` to HTML to capture client-side errors
187- **Error Handling:** Only use try...catch when there's a clear local resolution; Avoid catches that merely log or return 500s. Let errors bubble up with full context
188- **Environment Variables:** Use `Deno.env.get('keyname')` when you need to, but generally prefer APIs that don't require keys
189- **Imports:** Use `https://esm.sh` for npm and Deno dependencies to ensure compatibility on server and browser
190- **Storage Strategy:** Only use backend storage if explicitly required; prefer simple static client-side sites
224### Backend (Hono) Best Practices
225226- Hono is the recommended API framework
227- Main entry point should be `backend/index.ts`
228- **Static asset serving:** Use the utility functions to read and serve project files:
248});
249```
250- Create RESTful API routes for CRUD operations
251- Always include this snippet at the top-level Hono app to re-throwing errors to see full stack traces:
252```ts
285- For files in the project, use `readFile` helpers
2862875. **API Design:**
288- `fetch` handler is the entry point for HTTP vals
289- Run the Hono app with `export default app.fetch // This is the entry point for HTTP vals`
townie-testingtest-randomuser-api.ts10 matches
1export default async function(req: Request) {
2const url = new URL(req.url);
3const api = url.searchParams.get('api') || 'jsonplaceholder';
4
5try {
6let apiUrl: string;
7
8switch (api) {
9case 'jsonplaceholder':
10const randomUserId = Math.floor(Math.random() * 10) + 1; // Random int from 1 to 10
11apiUrl = `https://jsonplaceholder.typicode.com/users/${randomUserId}`;
12break;
13case 'httpbin':
14apiUrl = 'https://httpbin.org/json';
15break;
16case 'cat-facts':
17apiUrl = 'https://catfact.ninja/fact';
18break;
19case 'dog-api':
20apiUrl = 'https://dog.ceo/api/breeds/image/random';
21break;
22default:
23return new Response('Available APIs: jsonplaceholder, httpbin, cat-facts, dog-api\nUsage: ?api=jsonplaceholder', {
24headers: { 'Content-Type': 'text/plain' }
25});
26}
27
28const response = await fetch(apiUrl);
29
30if (!response.ok) {
10<meta charset="UTF-8">
11<meta name="viewport" content="width=device-width, initial-scale=1.0">
12<title>Test Person Enrichment API</title>
13<script src="https://cdn.twind.style" crossorigin></script>
14<script src="https://esm.town/v/std/catch"></script>
65<body>
66<div class="container">
67<h1>Test Person Enrichment API</h1>
68<p>Enter details below to test the endpoint: <code>${endpointUrl}</code></p>
69<form id="enrichmentForm">
openai_enrichmentindex.ts1 match
87// Initialize OpenAI client
88const client = new OpenAI({
89apiKey: Deno.env.get("OPENAI_API_KEY"),
90});
91
stevensDemosendDailyBrief.ts8 matches
9798export async function sendDailyBriefing(chatId?: string, today?: DateTime) {
99// Get API keys from environment
100const apiKey = Deno.env.get("ANTHROPIC_API_KEY");
101const telegramToken = Deno.env.get("TELEGRAM_TOKEN");
102106}
107108if (!apiKey) {
109console.error("Anthropic API key is not configured.");
110return;
111}
122123// Initialize Anthropic client
124const anthropic = new Anthropic({ apiKey });
125126// Initialize Telegram bot
162163// disabled title for now, it seemes unnecessary...
164// await bot.api.sendMessage(chatId, `*${title}*`, { parse_mode: "Markdown" });
165166// Then send the main content
169170if (content.length <= MAX_LENGTH) {
171await bot.api.sendMessage(chatId, content, { parse_mode: "Markdown" });
172// Store the briefing in chat history
173await storeChatMessage(
198// Send each chunk as a separate message and store in chat history
199for (const chunk of chunks) {
200await bot.api.sendMessage(chatId, chunk, { parse_mode: "Markdown" });
201// Store each chunk in chat history
202await storeChatMessage(