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/$%7BsvgDataUrl%7D?q=api&page=50&format=json

For typeahead suggestions, use the /typeahead endpoint:

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

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

Found 19573 results for "api"(7390ms)

hm-invoicesv1StatusProgress.tsx3 matches

@arfanโ€ขUpdated 2 days ago
64 {getStatusIcon(status, index)}
65 </span>
66 <span className="text-xs mt-1 capitalize">
67 {status}
68 </span>
76 <div className="text-sm opacity-70">
77 Step {currentIndex + 1} of {statuses.length}:
78 <span className="font-medium capitalize ml-1">{currentStatus}</span>
79 </div>
80 {interactive && currentIndex < statuses.length - 1 && (
124 max="100"
125 ></progress>
126 <span className="text-xs capitalize font-medium">
127 {currentStatus}
128 </span>

hm-invoicesv1App.tsx12 matches

@arfanโ€ขUpdated 2 days ago
2
3import React, { useState, useEffect } from "https://esm.sh/react@18.2.0";
4import { InvoiceWithVendor, Vendor, InvoiceFilters, InvoiceStats, InvoiceStatus, ApiResponse } from "../../shared/types.ts";
5import InvoiceList from "./InvoiceList.tsx";
6import InvoiceForm from "./InvoiceForm.tsx";
18 const [activeTab, setActiveTab] = useState<'dashboard' | 'invoices' | 'add'>('dashboard');
19
20 // Fetch data from API
21 useEffect(() => {
22 fetchData();
40
41 const [invoicesResponse, vendorsResponse] = await Promise.all([
42 fetch(`/api/invoices?${queryParams.toString()}`),
43 fetch('/api/vendors')
44 ]);
45
48 }
49
50 const invoicesData: ApiResponse<InvoiceWithVendor[]> = await invoicesResponse.json();
51 const vendorsData: ApiResponse<Vendor[]> = await vendorsResponse.json();
52
53 if (!invoicesData.success || !vendorsData.success) {
69 try {
70 setStatsLoading(true);
71 const response = await fetch('/api/invoices/stats');
72
73 if (!response.ok) {
75 }
76
77 const data: ApiResponse<InvoiceStats> = await response.json();
78
79 if (!data.success) {
92 const handleAddInvoice = async (invoiceData: any) => {
93 try {
94 const response = await fetch('/api/invoices', {
95 method: 'POST',
96 headers: {
104 }
105
106 const data: ApiResponse<InvoiceWithVendor> = await response.json();
107
108 if (!data.success) {
123 const handleStatusUpdate = async (invoiceId: number, newStatus: InvoiceStatus) => {
124 try {
125 const response = await fetch(`/api/invoices/${invoiceId}`, {
126 method: 'PUT',
127 headers: {
135 }
136
137 const data: ApiResponse<InvoiceWithVendor> = await response.json();
138
139 if (!data.success) {

hm-invoicesv1InvoiceList.tsx1 match

@arfanโ€ขUpdated 2 days ago
217 </div>
218 </td>
219 <td className="capitalize">{invoice.expected_day}</td>
220 <td>{new Date(invoice.invoice_date).toLocaleDateString()}</td>
221 <td>

hm-invoicesv1VAL-TOWN-RULES.md10 matches

@arfanโ€ขUpdated 2 days ago
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
24
25- Create web APIs and endpoints
26- Handle HTTP requests and responses
27- Example structure:
133However, it's *extremely importing* to note that `parseProject` and other Standard Library utilities ONLY RUN ON THE SERVER.
134If 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
135or by making an API request for it.
136
137## Val Town Platform Specifics
141- **AI Image:** To inline generate an AI image use: `<img src="https://maxm-imggenurl.web.val.run/the-description-of-your-image" />`
142- **Storage:** DO NOT use the Deno KV module for storage
143- **Browser APIs:** DO NOT use the `alert()`, `prompt()`, or `confirm()` methods
144- **Weather Data:** Use open-meteo for weather data (doesn't require API keys) unless otherwise specified
145- **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
146- **Error Debugging:** Add `<script src="https://esm.town/v/std/catch"></script>` to HTML to capture client-side errors
147- **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
148- **Environment Variables:** Use `Deno.env.get('keyname')` when you need to, but generally prefer APIs that don't require keys
149- **Imports:** Use `https://esm.sh` for npm and Deno dependencies to ensure compatibility on server and browser
150- **Storage Strategy:** Only use backend storage if explicitly required; prefer simple static client-side sites
371### Backend (Hono) Best Practices
372
373- Hono is the recommended API framework
374- Main entry point should be `main.tsx`
375- **Database Setup:** Use the admin utilities to handle table creation and seeding. Backend should focus on CRUD operations only
397 });
398 ```
399- Create RESTful API routes for CRUD operations
400- Always include this snippet at the top-level Hono app to re-throwing errors to see full stack traces:
401 ```ts
437 - For files in the project, use `readFile` helpers
438
4395. **API Design:**
440 - `fetch` handler is the entry point for HTTP vals
441 - Run the Hono app with `export default app.fetch // This is the entry point for HTTP vals`

hm-invoicesv1main.tsx64 matches

@arfanโ€ขUpdated 2 days ago
25 UpdateInvoiceRequest,
26 InvoiceFilters,
27 ApiResponse
28} from "./shared/types.ts";
29
70
71// ============================================================================
72// INVOICE API ENDPOINTS
73// ============================================================================
74
75// GET /api/invoices/stats - Dashboard statistics (must come before /:id route)
76app.get("/api/invoices/stats", async (c) => {
77 try {
78 const stats = await getInvoiceStats();
79
80 const response: ApiResponse<typeof stats> = {
81 success: true,
82 data: stats
85 return c.json(response);
86 } catch (error) {
87 const response: ApiResponse<null> = {
88 success: false,
89 error: error.message
93});
94
95// GET /api/invoices - List all invoices with filtering
96app.get("/api/invoices", async (c) => {
97 try {
98 const url = new URL(c.req.url);
120 const invoices = await getAllInvoices(filters);
121
122 const response: ApiResponse<typeof invoices> = {
123 success: true,
124 data: invoices
127 return c.json(response);
128 } catch (error) {
129 const response: ApiResponse<null> = {
130 success: false,
131 error: error.message
135});
136
137// GET /api/invoices/:id - Get specific invoice
138app.get("/api/invoices/:id", async (c) => {
139 try {
140 const id = parseInt(c.req.param('id'));
141 if (isNaN(id)) {
142 const response: ApiResponse<null> = {
143 success: false,
144 error: "Invalid invoice ID"
149 const invoice = await getInvoiceById(id);
150 if (!invoice) {
151 const response: ApiResponse<null> = {
152 success: false,
153 error: "Invoice not found"
156 }
157
158 const response: ApiResponse<typeof invoice> = {
159 success: true,
160 data: invoice
163 return c.json(response);
164 } catch (error) {
165 const response: ApiResponse<null> = {
166 success: false,
167 error: error.message
171});
172
173// POST /api/invoices - Create new invoice
174app.post("/api/invoices", async (c) => {
175 try {
176 const body = await c.req.json();
180
181 if (!vendor_id || !type || !expected_day || !invoice_date) {
182 const response: ApiResponse<null> = {
183 success: false,
184 error: "Missing required fields: vendor_id, type, expected_day, invoice_date"
189 // Validate field values
190 if (!isValidType(type)) {
191 const response: ApiResponse<null> = {
192 success: false,
193 error: `Invalid type. Must be one of: ${CONFIG.INVOICE_TYPES.join(', ')}`
197
198 if (!isValidDay(expected_day)) {
199 const response: ApiResponse<null> = {
200 success: false,
201 error: `Invalid expected_day. Must be one of: ${CONFIG.DAYS_OF_WEEK.join(', ')}`
207 const vendor = await getVendorById(vendor_id);
208 if (!vendor) {
209 const response: ApiResponse<null> = {
210 success: false,
211 error: "Vendor not found"
217 const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
218 if (!dateRegex.test(invoice_date)) {
219 const response: ApiResponse<null> = {
220 success: false,
221 error: "Invalid date format. Use YYYY-MM-DD"
234 const newInvoice = await getInvoiceById(invoiceId);
235
236 const response: ApiResponse<typeof newInvoice> = {
237 success: true,
238 data: newInvoice
241 return c.json(response, 201);
242 } catch (error) {
243 const response: ApiResponse<null> = {
244 success: false,
245 error: error.message
249});
250
251// PUT /api/invoices/:id - Update invoice (mainly status changes)
252app.put("/api/invoices/:id", async (c) => {
253 try {
254 const id = parseInt(c.req.param('id'));
255 if (isNaN(id)) {
256 const response: ApiResponse<null> = {
257 success: false,
258 error: "Invalid invoice ID"
264 const existingInvoice = await getInvoiceById(id);
265 if (!existingInvoice) {
266 const response: ApiResponse<null> = {
267 success: false,
268 error: "Invoice not found"
278 const vendor = await getVendorById(body.vendor_id);
279 if (!vendor) {
280 const response: ApiResponse<null> = {
281 success: false,
282 error: "Vendor not found"
289 if (body.type !== undefined) {
290 if (!isValidType(body.type)) {
291 const response: ApiResponse<null> = {
292 success: false,
293 error: `Invalid type. Must be one of: ${CONFIG.INVOICE_TYPES.join(', ')}`
300 if (body.expected_day !== undefined) {
301 if (!isValidDay(body.expected_day)) {
302 const response: ApiResponse<null> = {
303 success: false,
304 error: `Invalid expected_day. Must be one of: ${CONFIG.DAYS_OF_WEEK.join(', ')}`
311 if (body.status !== undefined) {
312 if (!isValidStatus(body.status)) {
313 const response: ApiResponse<null> = {
314 success: false,
315 error: `Invalid status. Must be one of: ${CONFIG.INVOICE_STATUSES.join(', ')}`
323 const dateRegex = /^\d{4}-\d{2}-\d{2}$/;
324 if (!dateRegex.test(body.invoice_date)) {
325 const response: ApiResponse<null> = {
326 success: false,
327 error: "Invalid date format. Use YYYY-MM-DD"
334 // Check if there are any updates
335 if (Object.keys(updates).length === 0) {
336 const response: ApiResponse<null> = {
337 success: false,
338 error: "No valid fields to update"
343 const success = await updateInvoice(id, updates);
344 if (!success) {
345 const response: ApiResponse<null> = {
346 success: false,
347 error: "Failed to update invoice"
352 const updatedInvoice = await getInvoiceById(id);
353
354 const response: ApiResponse<typeof updatedInvoice> = {
355 success: true,
356 data: updatedInvoice
359 return c.json(response);
360 } catch (error) {
361 const response: ApiResponse<null> = {
362 success: false,
363 error: error.message
367});
368
369// DELETE /api/invoices/:id - Delete invoice
370app.delete("/api/invoices/:id", async (c) => {
371 try {
372 const id = parseInt(c.req.param('id'));
373 if (isNaN(id)) {
374 const response: ApiResponse<null> = {
375 success: false,
376 error: "Invalid invoice ID"
382 const existingInvoice = await getInvoiceById(id);
383 if (!existingInvoice) {
384 const response: ApiResponse<null> = {
385 success: false,
386 error: "Invoice not found"
391 const success = await deleteInvoice(id);
392 if (!success) {
393 const response: ApiResponse<null> = {
394 success: false,
395 error: "Failed to delete invoice"
398 }
399
400 const response: ApiResponse<{ id: number }> = {
401 success: true,
402 data: { id }
405 return c.json(response);
406 } catch (error) {
407 const response: ApiResponse<null> = {
408 success: false,
409 error: error.message
414
415// ============================================================================
416// VENDOR API ENDPOINTS
417// ============================================================================
418
419// GET /api/vendors - List all vendors
420app.get("/api/vendors", async (c) => {
421 try {
422 const vendors = await getAllVendors();
423
424 const response: ApiResponse<typeof vendors> = {
425 success: true,
426 data: vendors
429 return c.json(response);
430 } catch (error) {
431 const response: ApiResponse<null> = {
432 success: false,
433 error: error.message
437});
438
439// GET /api/vendors/:id - Get specific vendor
440app.get("/api/vendors/:id", async (c) => {
441 try {
442 const id = parseInt(c.req.param('id'));
443 if (isNaN(id)) {
444 const response: ApiResponse<null> = {
445 success: false,
446 error: "Invalid vendor ID"
451 const vendor = await getVendorById(id);
452 if (!vendor) {
453 const response: ApiResponse<null> = {
454 success: false,
455 error: "Vendor not found"
458 }
459
460 const response: ApiResponse<typeof vendor> = {
461 success: true,
462 data: vendor
465 return c.json(response);
466 } catch (error) {
467 const response: ApiResponse<null> = {
468 success: false,
469 error: error.message
477// ============================================================================
478
479// POST /api/seed - Seed vendors (for admin use)
480app.post("/api/seed", async (c) => {
481 try {
482 const count = await seedVendors();
483 const newCounts = await getTableCounts();
484
485 const response: ApiResponse<{ seededCount: number; totalCounts: typeof newCounts }> = {
486 success: true,
487 data: {
493 return c.json(response);
494 } catch (error) {
495 const response: ApiResponse<null> = {
496 success: false,
497 error: error.message
501});
502
503// GET /api/test - Test database functionality
504app.get("/api/test", async (c) => {
505 try {
506 const counts = await getTableCounts();
507 const vendors = await getAllVendors();
508
509 const response: ApiResponse<{ counts: typeof counts; vendors: typeof vendors; totalVendors: number }> = {
510 success: true,
511 data: {
518 return c.json(response);
519 } catch (error) {
520 const response: ApiResponse<null> = {
521 success: false,
522 error: error.message

hm-invoicesv1InvoiceForm.tsx2 matches

@arfanโ€ขUpdated 2 days ago
67 onChange={() => setType(invoiceType)}
68 />
69 <span className="label-text ml-2 capitalize">{invoiceType}</span>
70 </label>
71 ))}
85 >
86 {CONFIG.DAYS_OF_WEEK.map(day => (
87 <option key={day} value={day} className="capitalize">{day}</option>
88 ))}
89 </select>

hm-invoicesv1vt-deploy.mdc2 matches

@arfanโ€ขUpdated 2 days ago
4alwaysApply: false
5---
6# command to use api key to push to val town
7
8VAL_TOWN_API_KEY=vtwn_J5YqHdcJA2g99RsZs7UXNFcCXGY vt push
9
10# current project HTTP endpoints

hm-invoicesv1db-viewer.tsx1 match

@arfanโ€ขUpdated 2 days ago
233 </span>
234 </td>
235 <td className="capitalize">{invoice.expected_day}</td>
236 <td className="font-mono">{invoice.invoice_date}</td>
237 <td>

api_ianmenethil_comapiServerGenerator.ts27 matches

@ianmenethilโ€ขUpdated 2 days ago
1#!/usr/bin/env -S deno run --allow-read --allow-write --allow-net
2/**
3 * api-server-generator.ts โ€” Template generator for creating new API servers from OpenAPI specs.
4 * Generates controller stubs, registry configuration, and basic server structure.
5 */
11interface ServerTemplate {
12 name: string;
13 openApiSpecPath: string;
14 outputDirectory: string;
15 controllers: ControllerInfo[];
31}
32
33export class APIServerGenerator {
34 /**
35 * Generate a new API server from OpenAPI specification
36 */
37 static async generateServer(template: ServerTemplate): Promise<void> {
38 console.log(`๐Ÿš€ Generating API server: ${template.name}`);
39 console.log(`๐Ÿ“‹ OpenAPI Spec: ${template.openApiSpecPath}`);
40 console.log(`๐Ÿ“ Output Directory: ${template.outputDirectory}`);
41
42 // 1. Parse OpenAPI spec
43 const spec = await this.parseOpenAPISpec(template.openApiSpecPath);
44
45 // 2. Extract controller information
61 await this.copyBaseFiles(template.outputDirectory);
62
63 console.log(`โœ… API server generated successfully in ${template.outputDirectory}`);
64 console.log(`๐Ÿ“ Next steps:`);
65 console.log(` 1. cd ${template.outputDirectory}`);
70
71 /**
72 * Parse OpenAPI specification file
73 */
74 private static async parseOpenAPISpec(specPath: string): Promise<any> {
75 try {
76 const content = await Deno.readTextFile(specPath);
85 } catch (error) {
86 const errorMessage = error instanceof Error ? error.message : String(error);
87 throw new Error(`Failed to parse OpenAPI spec: ${errorMessage}`);
88 }
89 }
90
91 /**
92 * Extract controller information from OpenAPI spec
93 */
94 private static extractControllers(spec: any): ControllerInfo[] {
96
97 if (!spec.paths) {
98 console.warn("No paths found in OpenAPI spec");
99 return [];
100 }
138
139 /**
140 * Create directory structure for new API server
141 */
142 private static async createDirectoryStructure(outputDir: string): Promise<void> {
145 "src/core",
146 "src/middleware",
147 "src/openapi",
148 "src/utils",
149 "src/types",
150 "src/external-apis",
151 "src/tests",
152 ];
362 ): string {
363 return `/**
364 * main.tsx โ€” Generated API server entry point
365 * Server: ${template.name}
366 */
369import { cors } from 'hono/cors';
370import { logger } from 'hono/logger';
371import { OpenAPIRouteGenerator } from './src/openapi/route.generator.ts';
372
373const app = new Hono();
386});
387
388// Initialize OpenAPI routes
389try {
390\tconst routeGenerator = new OpenAPIRouteGenerator(app);
391\tawait routeGenerator.loadAndGenerateRoutes('./src/openapi');
392\tconsole.log('โœ… Routes loaded successfully');
393} catch (error) {
417
418console.log(\`๐Ÿš€ Starting \${' ${template.name}'} server on port \${port}\`);
419console.log(\`๐Ÿ“š API Documentation: http://localhost:\${port}/docs\`);
420
421Deno.serve({ port }, app.fetch);
430 if (args.length < 3) {
431 console.log(
432 "Usage: deno run --allow-read --allow-write api-server-generator.ts <name> <openapi-spec> <output-dir>",
433 );
434 console.log(
435 "Example: deno run --allow-read --allow-write api-server-generator.ts MyAPI ./openapi.yaml ./my-api-server",
436 );
437 Deno.exit(1);
441
442 try {
443 await APIServerGenerator.generateServer({
444 name,
445 openApiSpecPath: specPath,
446 outputDirectory: outputDir,
447 controllers: [], // Will be extracted from spec

api_ianmenethil_comtokenEncryption.ts1 match

@ianmenethilโ€ขUpdated 2 days ago
1/**
2 * token.encryption.ts โ€” Token encryption/decryption utilities for OAuth tokens.
3 * Uses Web Crypto API for AES-GCM encryption to secure sensitive token data.
4 */
5

researchAgent2 file matches

@thesephistโ€ขUpdated 23 hours ago
This is a lightweight wrapper around Perplexity's web search API

memoryApiExample2 file matches

@ingenierotitoโ€ขUpdated 1 day ago
Kapil01
apiv1