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/$1?q=function&page=14&format=json

For typeahead suggestions, use the /typeahead endpoint:

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

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

Found 24676 results for "function"(992ms)

flyFlyApiClient.ts1 match

@chadparkerโ€ขUpdated 19 hours ago
47}
48
49// Base API client functions that can be imported by other files
50export class FlyApiClient {
51 private token: string;

flyindex.tsx2 matches

@chadparkerโ€ขUpdated 19 hours ago
1import { FlyApiClient } from "./FlyApiClient.ts";
2
3export default async function(req: Request): Promise<Response> {
4 try {
5 const client = new FlyApiClient();
111
112 // Add some interactivity
113 document.addEventListener('DOMContentLoaded', function() {
114 console.log('Fly.io Dashboard loaded with ${apps.length} apps');
115 });

ChatApp.tsx1 match

@c15rโ€ขUpdated 20 hours ago
34];
35
36export default function App() {
37 const [config, setConfig] = useState<AppConfig>({
38 anthropicApiKey: "",

Test2index.ts1 match

@lee_royโ€ขUpdated 21 hours ago
22// Initialize database on startup
23let dbInitialized = false;
24async function initializeDatabase() {
25 if (!dbInitialized) {
26 console.log('Initializing database...');

Test2validation.ts8 matches

@lee_royโ€ขUpdated 22 hours ago
23
24// Validation middleware factory
25export function validateBody(schema: ValidationSchema) {
26 return async (c: Context, next: Next) => {
27 try {
45
46// Validate query parameters
47export function validateQuery(schema: ValidationSchema) {
48 return async (c: Context, next: Next) => {
49 const query = Object.fromEntries(c.req.queries());
62}
63
64// Core validation function
65export function validateObject(obj: any, schema: ValidationSchema): ValidationError[] {
66 const errors: ValidationError[] = [];
67
76
77// Validate individual field
78function validateField(field: string, value: any, rule: ValidationRule): ValidationError[] {
79 const errors: ValidationError[] = [];
80
142
143// Type validation
144function validateType(field: string, value: any, type: string): ValidationError | null {
145 switch (type) {
146 case 'string':
302
303// Helper to get validated body from context
304export function getValidatedBody<T = any>(c: Context): T {
305 return c.get('validatedBody');
306}
307
308// Helper to get validated query from context
309export function getValidatedQuery<T = any>(c: Context): T {
310 return c.get('validatedQuery');
311}

Test2auth.ts6 matches

@lee_royโ€ขUpdated 22 hours ago
133
134// Authentication middleware
135export async function authMiddleware(c: Context, next: Next) {
136 const authHeader = c.req.header('Authorization');
137
159
160// Optional authentication middleware (doesn't fail if no token)
161export async function optionalAuthMiddleware(c: Context, next: Next) {
162 const authHeader = c.req.header('Authorization');
163
181
182// Admin role middleware
183export async function adminMiddleware(c: Context, next: Next) {
184 const user = c.get('user') as User;
185
192
193// Customer role middleware (customer or admin)
194export async function customerMiddleware(c: Context, next: Next) {
195 const user = c.get('user') as User;
196
203
204// Get current user helper
205export function getCurrentUser(c: Context): User | null {
206 return c.get('user') || null;
207}
208
209// Check if user has permission
210export function hasPermission(user: User | null, requiredRole: 'customer' | 'admin'): boolean {
211 if (!user) return false;
212

Test2queries.ts1 match

@lee_royโ€ขUpdated 22 hours ago
1// Database query functions for IoT Solutions platform
2
3import { sqlite } from "https://esm.town/v/stevekrouse/sqlite";

Test2migrations.ts5 matches

@lee_royโ€ขUpdated 22 hours ago
6 * Initialize all database tables
7 */
8export async function runMigrations(): Promise<void> {
9 console.log('Running database migrations...');
10
235 * Create database indexes for better query performance
236 */
237async function createIndexes(): Promise<void> {
238 const indexes = [
239 'CREATE INDEX IF NOT EXISTS idx_users_email ON users(email)',
266 * Insert default data for categories, solutions, and admin user
267 */
268async function insertDefaultData(): Promise<void> {
269 // Check if data already exists
270 const existingCategories = await sqlite.execute('SELECT COUNT(*) as count FROM categories');
407 * Create default admin user if none exists
408 */
409export async function createDefaultAdmin(): Promise<void> {
410 const adminEmail = Deno.env.get('ADMIN_EMAIL') || 'admin@iotcompany.com';
411 const adminPassword = Deno.env.get('ADMIN_PASSWORD') || 'admin123!';
437 * Simple password hashing (use bcrypt in production)
438 */
439async function hashPassword(password: string): Promise<string> {
440 const encoder = new TextEncoder();
441 const data = encoder.encode(password + 'salt123'); // Add proper salt in production

Test2utils.ts22 matches

@lee_royโ€ขUpdated 22 hours ago
1// Shared utility functions for the IoT Solutions platform
2
3import type { ValidationError, FormErrors } from './types.ts';
6 * Format currency values
7 */
8export function formatCurrency(amount: number, currency = 'USD'): string {
9 return new Intl.NumberFormat('en-US', {
10 style: 'currency',
16 * Format dates consistently
17 */
18export function formatDate(date: string | Date, options?: Intl.DateTimeFormatOptions): string {
19 const dateObj = typeof date === 'string' ? new Date(date) : date;
20 return new Intl.DateTimeFormat('en-US', {
29 * Format date and time
30 */
31export function formatDateTime(date: string | Date): string {
32 return formatDate(date, {
33 year: 'numeric',
42 * Generate a slug from a string
43 */
44export function generateSlug(text: string): string {
45 return text
46 .toLowerCase()
53 * Generate a random order number
54 */
55export function generateOrderNumber(): string {
56 const timestamp = Date.now().toString(36);
57 const random = Math.random().toString(36).substr(2, 5);
62 * Validate email format
63 */
64export function isValidEmail(email: string): boolean {
65 const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
66 return emailRegex.test(email);
70 * Validate phone number (basic US format)
71 */
72export function isValidPhone(phone: string): boolean {
73 const phoneRegex = /^\+?1?[-.\s]?\(?([0-9]{3})\)?[-.\s]?([0-9]{3})[-.\s]?([0-9]{4})$/;
74 return phoneRegex.test(phone);
78 * Validate password strength
79 */
80export function validatePassword(password: string): ValidationError[] {
81 const errors: ValidationError[] = [];
82
103 * Convert validation errors array to form errors object
104 */
105export function validationErrorsToFormErrors(errors: ValidationError[]): FormErrors {
106 return errors.reduce((acc, error) => {
107 acc[error.field] = error.message;
111
112/**
113 * Debounce function for search inputs
114 */
115export function debounce<T extends (...args: any[]) => any>(
116 func: T,
117 wait: number
127 * Calculate order totals
128 */
129export function calculateOrderTotals(
130 subtotal: number,
131 taxRate = 0.08,
146 * Calculate shipping cost based on order value and weight
147 */
148export function calculateShipping(orderValue: number, weight = 1): number {
149 // Free shipping over $500
150 if (orderValue >= 500) return 0;
160 * Truncate text to specified length
161 */
162export function truncateText(text: string, maxLength: number): string {
163 if (text.length <= maxLength) return text;
164 return text.substr(0, maxLength - 3) + '...';
168 * Get initials from name
169 */
170export function getInitials(firstName: string, lastName: string): string {
171 return `${firstName.charAt(0)}${lastName.charAt(0)}`.toUpperCase();
172}
175 * Format file size
176 */
177export function formatFileSize(bytes: number): string {
178 const sizes = ['Bytes', 'KB', 'MB', 'GB'];
179 if (bytes === 0) return '0 Bytes';
185 * Generate a random color for avatars
186 */
187export function generateAvatarColor(seed: string): string {
188 const colors = [
189 '#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7',
202 * Check if user has permission
203 */
204export function hasPermission(userRole: string, requiredRole: string): boolean {
205 const roleHierarchy = { customer: 0, admin: 1 };
206 return roleHierarchy[userRole as keyof typeof roleHierarchy] >=
211 * Deep clone an object
212 */
213export function deepClone<T>(obj: T): T {
214 if (obj === null || typeof obj !== 'object') return obj;
215 if (obj instanceof Date) return new Date(obj.getTime()) as unknown as T;
230 * Convert search params to query string
231 */
232export function buildQueryString(params: Record<string, any>): string {
233 const searchParams = new URLSearchParams();
234
245 * Parse query string to object
246 */
247export function parseQueryString(queryString: string): Record<string, string> {
248 const params = new URLSearchParams(queryString);
249 const result: Record<string, string> = {};

Test2README.md3 matches

@lee_royโ€ขUpdated 22 hours ago
5## ๐Ÿš€ Features
6
7### Core Functionality
8- **Product Storefront**: Browse IoT devices, view specs, add to cart, secure checkout
9- **IoT Solutions Portal**: Showcase vertical solutions with lead capture
27โ”‚ โ”œโ”€โ”€ database/
28โ”‚ โ”‚ โ”œโ”€โ”€ migrations.ts # Database schema setup
29โ”‚ โ”‚ โ”œโ”€โ”€ queries.ts # Database query functions
30โ”‚ โ”‚ โ””โ”€โ”€ README.md
31โ”‚ โ”œโ”€โ”€ routes/
60โ”‚ โ”œโ”€โ”€ types.ts # Shared TypeScript types
61โ”‚ โ”œโ”€โ”€ constants.ts # Shared constants
62โ”‚ โ””โ”€โ”€ utils.ts # Shared utility functions
63โ””โ”€โ”€ README.md
64```

getFileEmail4 file matches

@shouserโ€ขUpdated 1 month ago
A helper function to build a file's email
tuna

tuna8 file matches

@jxnblkโ€ขUpdated 1 month ago
Simple functional CSS library for Val Town
lost1991
import { OpenAI } from "https://esm.town/v/std/openai"; export default async function(req: Request): Promise<Response> { if (req.method === "OPTIONS") { return new Response(null, { headers: { "Access-Control-Allow-Origin": "*",
webup
LangChain (https://langchain.com) Ambassador, KubeSphere (https://kubesphere.io) Ambassador, CNCF OpenFunction (https://openfunction.dev) TOC Member.